how to send HttpRequest and get Json response in android?
73,261
Solution 1
Try below code to get json from a URL
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget= new HttpGet(URL);
HttpResponse response = httpclient.execute(httpget);
if(response.getStatusLine().getStatusCode()==200){
String server_response = EntityUtils.toString(response.getEntity());
Log.i("Server response", server_response );
} else {
Log.i("Server response", "Failed to get server response" );
}
Solution 2
Use this function to get JSON from URL.
public static JSONObject getJSONObjectFromURL(String urlString) throws IOException, JSONException {
HttpURLConnection urlConnection = null;
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */ );
urlConnection.setConnectTimeout(15000 /* milliseconds */ );
urlConnection.setDoOutput(true);
urlConnection.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
String jsonString = sb.toString();
System.out.println("JSON: " + jsonString);
return new JSONObject(jsonString);
}
Do not forget to add Internet permission in your manifest
<uses-permission android:name="android.permission.INTERNET" />
Then use it like this:
try{
JSONObject jsonObject = getJSONObjectFromURL(urlString);
//
// Parse your json here
//
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Author by
moosavi
Updated on July 08, 2020Comments
-
moosavi almost 4 years
i want to build an android app for my wordpress website using wp-api plugin. how can i send HttpRequest(GET) and recive response in Json?
-
Tarion about 7 yearsWhere to find the HttpClient? What package I have to include?
-
RestingRobot about 7 yearsNice solution, doesn't require importing the apache http client!
-
Mohammedsalim Shivani almost 7 years@Tarion just add
useLibrary 'org.apache.http.legacy'
in your app level build.gradle file inandroid
block abovedefaultConfig
. -
Victor Sergienko over 6 yearsAt least two major errors here. 1.
urlConnection.setDoOutput(true);
changes request toPOST
method. 2. It effectively executes two requests,new InputStreamReader(url.openStream()
opensurl
once again, disregardingurlConnection
and all of its properties. 3.sb.append(line + "\n")
constructs an excessString
. -
kPieczonka over 5 yearsthis is a deprecated method. Android studio will give you warning over it. Consider using volley for network requests. see developer.android.com/training/volley/simple