Android HTTP POST params发送但服务器无法获取它

时间:2014-02-18 11:20:58

标签: java android rest http-post httpclient

调用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);

我没有在服务器端获得post params。得到param的作品。相同的API适用于其他REST客户端,但不适用于Android。

1 个答案:

答案 0 :(得分:1)

变量httpRequest没用。变量postParameters是String吗?

这里用一些参数发送帖子上传图片的例子。

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);
}

在您的代码中,它可以像这样

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);