0

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.

Goo
  • 1,318
  • 1
  • 13
  • 31
Uhehesh
  • 506
  • 2
  • 8
  • 22
  • 1
    First off all you can put your code here, so people can help you with your problem, it might be just a simple UrlEncoding or a simple client configuration. – hackp0int Jun 30 '12 at 19:03
  • Exact duplicate: http://stackoverflow.com/questions/3505930/make-in-http-request-with-android – Thomas Dignan Jun 30 '12 at 19:42
  • @TomDignan no, there's GET there and that solution doesn't work for me. – Uhehesh Jun 30 '12 at 19:46
  • I solved my problem. It works on my phone but crashes on the emulator. However, can anyone help me how to fix that? I want to test my programs on emulator. – Uhehesh Jun 30 '12 at 21:02

1 Answers1

1

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.

Moog
  • 10,193
  • 2
  • 40
  • 66
  • 1
    Your comment indicated that you still have a crashing problem ... adding a generic excpetion catch will prevent that from happening. Use Log statements to find out what is happening. – Moog Jul 02 '12 at 16:57