How to Use the Simple Http Client in Android

How do I use the Simple HTTP client in Android?


public static void connect(String url)
{

HttpClient httpclient = new DefaultHttpClient();

// Prepare a request object
HttpGet httpget = new HttpGet(url);

// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda",response.getStatusLine().toString());

// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release

if (entity != null) {

// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}


} catch (Exception e) {}
}

private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

Make an HTTP request with android


UPDATE

This is a very old answer. I definitely won't recommend Apache's client anymore. Instead use either:

  • Retrofit
  • OkHttp
  • Volley
  • HttpUrlConnection

Original Answer

First of all, request a permission to access network, add following to your manifest:

<uses-permission android:name="android.permission.INTERNET" />

Then the easiest way is to use Apache http client bundled with Android:

    HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(URL));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
String responseString = out.toString();
out.close();
//..more logic
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}

If you want it to run on separate thread I'd recommend extending AsyncTask:

class RequestTask extends AsyncTask<String, String, String>{

@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}

You then can make a request by:

   new RequestTask().execute("http://stackoverflow.com");

How can I make a simple HTTP request in MainActivity.java? (Android Studio)

You should not make network requests on the main thread. The delay is unpredictable and it could freeze the UI.

Android force this behaviour by throwing an exception if you use the HttpUrlConnection object from the main thread.

You should then make your network request in the background, and then update the UI on the main thread. The AsyncTask class can be very handy for this use case !

private class GetUrlContentTask extends AsyncTask<String, Integer, String> {
protected String doInBackground(String... urls) {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String content = "", line;
while ((line = rd.readLine()) != null) {
content += line + "\n";
}
return content;
}

protected void onProgressUpdate(Integer... progress) {
}

protected void onPostExecute(String result) {
// this is executed on the main thread after the process is over
// update your UI here
displayMessage(result);
}
}

And you start this process this way:

new GetUrlContentTask().execute(sUrl)

Android project using httpclient -- http.client (apache), post/get method

The easiest way to answer my question is to show you the class that I made :

public class HTTPHelp{

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
private boolean abort;
private String ret;

HttpResponse response = null;
HttpPost httpPost = null;

public HTTPHelp(){

}

public void clearCookies() {

httpClient.getCookieStore().clear();

}

public void abort() {

try {
if(httpClient!=null){
System.out.println("Abort.");
httpPost.abort();
abort = true;
}
} catch (Exception e) {
System.out.println("HTTPHelp : Abort Exception : "+e);
}
}

public String postPage(String url, String data, boolean returnAddr) {

ret = null;

httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);

httpPost = new HttpPost(url);
response = null;

StringEntity tmp = null;

httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux " +
"i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
httpPost.setHeader("Accept", "text/html,application/xml," +
"application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

try {
tmp = new StringEntity(data,"UTF-8");
} catch (UnsupportedEncodingException e) {
System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);
}

httpPost.setEntity(tmp);

try {
response = httpClient.execute(httpPost,localContext);
} catch (ClientProtocolException e) {
System.out.println("HTTPHelp : ClientProtocolException : "+e);
} catch (IOException e) {
System.out.println("HTTPHelp : IOException : "+e);
}
ret = response.getStatusLine().toString();

return ret;
}
}

I used this tutorial to do my post method and thoses examples

Android Simple HTTP Request?

I would check to make sure that,

  1. If there is an exception being thrown, investigate what is causing the IOException
  2. Your server could potentially be returning a non-200 response code.

Put in some breakpoints and see whats happening there. My bet is on the response code.

HTTP Request in Android with Kotlin

For Android, Volley is a good place to get started. For all platforms, you might also want to check out ktor client or http4k which are both good libraries.

However, you can also use standard Java libraries like java.net.HttpURLConnection
which is part of the Java SDK:

fun sendGet() {
val url = URL("http://www.google.com/")

with(url.openConnection() as HttpURLConnection) {
requestMethod = "GET" // optional default is GET

println("\nSent 'GET' request to URL : $url; Response Code : $responseCode")

inputStream.bufferedReader().use {
it.lines().forEach { line ->
println(line)
}
}
}
}

Or simpler:

URL("https://google.com").readText()

Using HttpClient and HttpPost in Android with post parameters

have you tried doing it without the JSON object and just passed two basicnamevaluepairs?
also, it might have something to do with your serversettings

Update:
this is a piece of code I use:

InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate));

try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(connection);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.d("HTTP", "HTTP: OK");
} catch (Exception e) {
Log.e("HTTP", "Error in http connection " + e.toString());
}


Related Topics



Leave a reply



Submit