Skip to content

Instantly share code, notes, and snippets.

@dhanifudin
Created October 9, 2018 04:26
Show Gist options
  • Save dhanifudin/b28b3a0e61b8e3632c70cecba2563352 to your computer and use it in GitHub Desktop.
Save dhanifudin/b28b3a0e61b8e3632c70cecba2563352 to your computer and use it in GitHub Desktop.
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpRequest {
public static String aksesInternet(String urlParam) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String jsonStr = null;
try {
URL url = new URL(urlParam);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
jsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line = reader.readLine()) != null) {
buffer.append(line).append("\n");
}
if (buffer.length() != 0) {
jsonStr = buffer.toString();
}
} catch (IOException e) {
Log.e("HttpRequest", "Error", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("HttpRequest", "Error closing stream", e);
}
}
}
return jsonStr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment