How to get Json Response by hitting Url
public class MainActivity extends Activity {
String url = "http://api.androidhive.info/contacts/";
String jsonResponse = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Response().execute();
}
class Response extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpresponse = httpClient.execute(httpPost);
HttpEntity entity = httpresponse.getEntity();
jsonResponse = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
Note:
- Network operations should not be in userthread so that you have to use either async task or thread handler structure
- Internet permission should be mentioned in android manifest file
No comments:
Post a Comment