views:

162

answers:

3

Hi all,

Have search everywhere but I couldn't find my answer, is there a way to make an simple HTTP request? I want to request an PHP page / script on one of my website but I don't want to show the webpage.

If possible I even want to do it in the background (in an BroadcastReceiver)

A: 

With a thread:

private class LoadingThread extends Thread{
  Handler handler;

  LoadingThread(Handler h) {
   handler = h;
  }
  @Override
  public void run() {
   Message m = handler.obtainMessage();
   try {
    BufferedReader in = new BufferedReader(
      new InputStreamReader(url.openStream()));
    String page= "";
    String inLine;
    while ((inLine = in.readLine()) != null){
     page += inLine;
    }
    in.close();
    Bundle b = new Bundle();
    b.putString("result", page);
    m.setData(b);
   } catch (MalformedURLException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
   handler.sendMessage(m);
  }
 }
fredley
+4  A: 

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() == SC_OK){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        out.close();
        String responseString = out.toString();
        //..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);
                out.close();
                responseString = out.toString();
            } 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");
Konstantin Burov
Does this create a thread to make the request or does it block?
fredley
See the update. AsyncTask is the best way to deal with background work on Android. Here is a good tutorial http://www.screaming-penguin.com/node/7746
Konstantin Burov
Here is an article from the official android developer blog on AsyncTask: http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html
Austyn Mahoney
+1  A: 

unless you have an explicit reason to choose the Apache HttpClient, you should prefer java.net.URLConnection. you can find plenty of examples of how to use it on the web. for example: http://download.oracle.com/javase/tutorial/networking/urls/readingWriting.html

we'll be improving the Android documentation in this regard in future releases.

Elliott Hughes