3

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?

user568021
  • 1,426
  • 5
  • 28
  • 55

2 Answers2

4

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"/> 
Nanne
  • 64,065
  • 16
  • 119
  • 163
3

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.

Harry Joy
  • 58,650
  • 30
  • 162
  • 207
  • `readStream` and `writeStream` are just placeholder, which tells you need to read the stream at here and process further. – Harry Joy Jun 25 '13 at 11:15