Skip to content

Instantly share code, notes, and snippets.

@xxhdpi
Created March 25, 2017 11:35
Show Gist options
  • Select an option

  • Save xxhdpi/0a2c0b3e6ab8ec77a2571e59ad62928d to your computer and use it in GitHub Desktop.

Select an option

Save xxhdpi/0a2c0b3e6ab8ec77a2571e59ad62928d to your computer and use it in GitHub Desktop.
/**
* baca data dari http connection
*/
private String ambilDataFromURL(URL url) throws IOException {
// define inputStream
InputStream inputStream = null;
// define HttpURLConnection
HttpURLConnection httpURLConnection = null;
String hasil = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
// Timeout for connection.connect() arbitrarily set to 3000ms.
httpURLConnection.setConnectTimeout(3000);
// For this use case, set HTTP method to GET.
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
// Retrieve the response body as an InputStream.
inputStream = httpURLConnection.getInputStream();
if (inputStream != null) {
// Converts Stream to String with max length of 500.
hasil = readStream(inputStream, 500);
}
} finally {
// Close Stream and disconnect HTTPS connection.
if (inputStream != null) {
inputStream.close();
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return hasil;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment