In most of the android applications it is essential that app may need to connect to internet and make some HTTP requests. In this tutorial i’ll be demonstrating about making simple HTTP Requests/Calls in Android.
There are several steps in HTTP Requests. So read all steps one by one :
1 2 |
// Creating HTTP client HttpClient httpClient = new DefaultHttpClient(); |
1 2 |
// Creating HTTP Post HttpPost httpPost = new HttpPost("your url"); |
1 2 3 4 5 |
// Building post parameters, key and value pair List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3); nameValuePair.add(new BasicNameValuePair("password", "your_password")); nameValuePair.add(new BasicNameValuePair("phone", "9887711222")); |
1 2 3 4 5 6 7 8 |
// Url Encoding the POST parameters try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair)); } catch (UnsupportedEncodingException e) { // writing error to Log e.printStackTrace(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Making HTTP Request try { HttpResponse response = httpClient.execute(httpPost); // writing response to log Log.d("Http Response:", response.toString()); } catch (ClientProtocolException e) { // writing exception to log e.printStackTrace(); } catch (IOException e) { // writing exception to log e.printStackTrace(); } |
1 2 |
/ Creating HTTP client HttpClient httpClient = new DefaultHttpClient(); |
1 2 |
//Creating Http Get HttpGet request = new HttpGet("your url"); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Making HTTP Request try { HttpResponse response = httpClient.execute(httpPost); // writing response to log Log.d("Http Response:", response.toString()); } catch (ClientProtocolException e) { // writing exception to log e.printStackTrace(); } catch (IOException e) { // writing exception to log e.printStackTrace(); } |
1 2 |
//Creating Http Entity HttpEntity entity = response.getEntity(); |
1 2 |
//Getting entity data in string String data = EntityUtils.toString(entity); |
Finally, you are ready to work on HTTP Requests.
Thanks.
Subscribe to us and get the latest news.