简体   繁体   中英

Android HTTP POST params send but server doesn't get it

Calling of API

    HttpUriRequest httpRequest = null;
    HttpPost request = new HttpPost(url);

    String postParameters = "email=" + email + "&name=" + name;

    StringEntity stringEntity = new StringEntity(postParameters, "UTF-8");
    request.setEntity(stringEntity);

    httpRequest = request;

    response = client.execute(httpRequest);

I am not getting post params at server side. Get param works. The same API works from other REST clients but not from android.

Variable httpRequest is useless. Is variable postParameters a String?

Here example of sending post to upload image with some params.

HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost(getString(R.string.url));

try {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    builder.addPart("picture", new FileBody(mSharedImagePath, ContentType.create("image/jpeg")));

    // Adding params
    List<NameValuePair> params = new ArrayList<NameValuePair>();

    params.add(new BasicNameValuePair("param1", "utf-8 encoded text");
    params.add(new BasicNameValuePair("param2", "another utf-8 encoded text");

    for (NameValuePair param : params) {
        builder.addTextBody(param.getName(), param.getValue(), ContentType.create("text/plain", Charset.forName("UTF-8")));
    }

    builder.setCharset(MIME.UTF8_CHARSET);
    httppost.setEntity(builder.build());

    HttpResponse response = httpclient.execute(httppost);

    HttpEntity resEntity = response.getEntity();
    resEntity.getContentLength();
    //......

} catch (FileNotFoundException e) {
    Logger.getInstance().log(e);
} catch (ClientProtocolException e) {
    Logger.getInstance().log(e);
} catch (IOException e) {
    Logger.getInstance().log(e);
} catch (Exception e) {
    Logger.getInstance().log(e);
}

In your code it can be like this

HttpPost request = new HttpPost(url);

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
nameValuePairs.add(new BasicNameValuePair("email","my email"));  
nameValuePairs.add(new BasicNameValuePair("name","my name"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

response = client.execute(request);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM