Skip to content

Instantly share code, notes, and snippets.

@talhahasanzia
Last active June 14, 2016 04:11
Show Gist options
  • Save talhahasanzia/d687ac0583ee921ea66e4d56b9bcd4b5 to your computer and use it in GitHub Desktop.
Save talhahasanzia/d687ac0583ee921ea66e4d56b9bcd4b5 to your computer and use it in GitHub Desktop.
Code sample for getting a json response from a server using url.
public class JsonResponse extends AsyncTask<String, Void, String>
{
String finalData = null;
@Override
protected String doInBackground(String... params)
{
Uri.Builder ub = new Uri.Builder();
ub.scheme("http").authority("api.someapi.com").appendPath("somepath")
.appendQueryParameter("lng", "")
.appendQueryParameter("lat", "")
.appendQueryParameter("mode", "json");
try {
URL requestUrl = new URL(ub.toString()); // set link
HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection(); // create connection
connection.setRequestMethod("GET"); // set HTTP Method type
connection.connect(); // connect to server
int responseCode = connection.getResponseCode(); // get response code from server
if (responseCode == HttpURLConnection.HTTP_OK) { // check if server says "Ok! i will respond to your request"
finalData = "";
BufferedReader reader = null; //Get buffer ready
InputStream inputStream = connection.getInputStream(); // get input stream from server ready
if (inputStream == null) { // if there is nothing in stream
return "";
}
reader = new BufferedReader(new InputStreamReader(inputStream)); // else pass stream data to buffer
String line;
while ((line = reader.readLine()) != null) { // read each line
finalData += line; // save them to string
}
if (finalData.length() == 0) { // check if string is empty
return "";
}
} else {
Log.i("Unsuccessful", "Unsuccessful HTTP Response Code: " + responseCode);
}
} catch (MalformedURLException e) {
Log.e("Wrong URL", e.getMessage().toString(), e);
} catch (IOException e) {
Log.e("Error", "Error connecting to API", e);
}
return finalData;
}
@Override
protected void onPostExecute(String result)
{
Log.d("JSON RESULT", result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment