0

I have searched everywhere but I couldn't find an answer, how can i make a HTTP request? I tried several possibilities, but none of them work. I keep getting errors.

InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;

try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d("Debug:", "The response is: " + response);
is = conn.getInputStream();

// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;

// Makes sure that the InputStream is closed after the app is
// finished using it.
}
catch(Exception ex)
{
    Log.v("Message: ", ex.getMessage());
    return "Helemaal niks!";
}
finally {
    if (is != null) {
        is.close();
    }
}

02-27 17:52:58.611 13571-13571/com.example.app E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.IllegalStateException: Could not execute method of the activity at android.view.View$1.onClick(View.java:3838) at android.view.View.performClick(View.java:4475) at android.view.View$PerformClick.run(View.java:18786) at android.os.Handler.handleCallback(Handler.java:730) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5419) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:525) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) at dalvik.system.NativeStart.main(Native Method)

R Pelzer
  • 1,188
  • 14
  • 34
  • did you add the android.permission.INTERNET in your manifest? – Martin Cazares Feb 27 '14 at 17:01
  • I added that permission, i got the following error:13571-13571/com.example.app E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.IllegalStateException: Could not execute method of the activity – R Pelzer Feb 27 '14 at 17:02
  • Please include the *complete* error message (ideally the whole stack trace - which you should be logging, not just the message) in your question, not in a comment. Also, format the code in your question to make it a *lot* more readable. – Jon Skeet Feb 27 '14 at 17:04
  • @HenkdeJager are you executing that code in a background thread? – Martin Cazares Feb 27 '14 at 17:05
  • How can i edit the message and add the log, without getting the error that is needs to be the right 'stockoverflow' format? – R Pelzer Feb 27 '14 at 17:10
  • I hardcoded the code under a button – R Pelzer Feb 27 '14 at 17:11
  • http://stackoverflow.com/questions/3505930/make-an-http-request-with-android – Merlevede Feb 27 '14 at 17:20

2 Answers2

0

If you only want to make an HTTP get request, you can use this code instead of your code.

try{
    String result = null;
    HttpClient httpClient = new DefaultHttpClient();
    String myUrl = "your url";
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(myUrl);
    HttpResponse response = httpClient.execute(httpGet, localContext);

    BufferedReader reader = new BufferedReader(new InputStreamReader(
            response.getEntity().getContent()));

    String line = null;
    while ((line = reader.readLine()) != null) {
        result += line + "\n";
    }
    return result;
}catch(Exception ex)
{
    Log.v("Message: ", ex.getMessage());
    return "Helemaal niks!";
}
enadun
  • 3,107
  • 3
  • 31
  • 34
0

All the webservice calls and etc should always be done inside an AsyncTask.

This helps it in executing without making the app to wait.

Below is a sample code which can help you to understand how to make a webcall.

try {


        HttpClient httpclient = new DefaultHttpClient();

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 2000);
        HttpConnectionParams.setSoTimeout(httpParameters, 2000);
        httpclient = new DefaultHttpClient(httpParameters);

        HttpGet request = new HttpGet(Constants.CHECK_UPDATE_URL);

        String responseString = null;

        HttpResponse response = httpclient.execute(request);
        StatusLine statusLine = response.getStatusLine();

        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {

            // Logging Server Responded

            LogActions.systemActions("Server Responded");

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();


                            //do your tasks here

        }

    } catch (Exception e) {

        Log.e("Exception", "An impossible exception", e);
    }
Atish Agrawal
  • 2,857
  • 1
  • 23
  • 38