Http get request in Android

11,285

Solution 1

If you want some demo code then try following:

 URL url = new URL("url.com");
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
   } finally {
     urlConnection.disconnect();
   }

and this:

   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     urlConnection.setDoOutput(true);
     urlConnection.setChunkedStreamingMode(0);

     OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
     writeStream(out);

     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
   } finally {
     urlConnection.disconnect();
   }

Hope this helps.

Solution 2

Very hard to tell without the actual error message. Random thought: did you add the internet permission to you manifest?

 <uses-permission android:name="android.permission.INTERNET"/> 
Share:
11,285
user568021
Author by

user568021

Besides all I'm a linux enthusiast...

Updated on June 04, 2022

Comments

  • user568021
    user568021 about 2 years

    I need help with sending http get request. Like this:

    URL connectURL;
    connectURL = new URL(address);
    HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection(); 
    // do some setup
    conn.setDoInput(true); 
    conn.setDoOutput(true); 
    conn.setUseCaches(false); 
    conn.setRequestMethod("GET"); 
    // connect and flush the request out
    conn.connect();
    conn.getOutputStream().flush();
    // now fetch the results
    String response = getResponse(conn);
    et.setText(response);
    

    I searched the web but any method I try, the code fails at 'conn.connect();'. Any clues?

  • Harry Joy
    Harry Joy about 11 years
    readStream and writeStream are just placeholder, which tells you need to read the stream at here and process further.