Uhehesh
Uhehesh

Reputation: 516

Can't finally perform HTTP POST request

I work on my first Android application and I have some great problems with trying to make HTTP POST request and receive response. These are few facts:

  1. I have INTERNET permission in AndroidManifest.xml: <uses-permission android:name="android.permission.INTERNET" />
  2. I tried many solutions. Solutions with URLConnection or HttpURLConnection don't work because they return empty string. Solution with HttpClient and HttpPost fails on execute() - I was googling for an hour but didn't find out how to fix that.
  3. There is internet connection. But I don't know how to fix my problem and finally to send HTTP POST request.

upd: e.g. this code makes my program crash:

public static APIResponse getResponse(String action, Map<String, String> params) throws IOException {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://google.com");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
    return null;
}

upd 2: it works on my phone but doesn't work on emulator! how to fix that behaviour on emulator?

upd 3: fixed.

Upvotes: 0

Views: 2267

Answers (1)

Moog
Moog

Reputation: 10193

Look at the example for HTTP Post

You should also employ fiddler2 to help debug your HTTP messages.

Also please note that you are not catching all exceptions properly ... you can add a generic catch statement at the end to prevent your app from crashing and help you figure out where the problem lies. Could be a timeout or similar.

Upvotes: 1

Related Questions