Apache HTTP客户端,POST请求.如何正确设置请求参数? [英] Apache HTTP Client, POST request. How to correctly set request parameters?

查看:1523
本文介绍了Apache HTTP客户端,POST请求.如何正确设置请求参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Apache HTTP Client,需要将POST请求发送到我的servlet. 发送请求时,我的servlet没有收到任何参数(在HttpServletRequest中).

I'm using Apache HTTP Client and I need to send a POST request to my servlet. When the request is sent my servlet does not receive any parameters (in the HttpServletRequest).

这是客户端程序代码:

// Engage the HTTP client
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
    HttpPost httpPost = new HttpPost("http://localhost:8080/test-json-web/JSONReceiverServlet");

    // Setup the request parameters
    HttpParams params = new BasicHttpParams();
    params.setParameter("taskdef", task1JsonString);
    httpPost.setParams(params);

    // Make the request
    response = httpclient.execute(httpPost);

    HttpEntity responseEntity = response.getEntity();

    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    if(responseEntity != null) {
        System.out.println("Response content length: " + responseEntity.getContentLength());
    }

    String jsonResultString = EntityUtils.toString(responseEntity);
    EntityUtils.consume(responseEntity);
    System.out.println("----------------------------------------");
    System.out.println("result:");
    System.out.println();
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    httpclient.getConnectionManager().shutdown();
}

如何正确设置POST请求参数,以便servlet实际接收它们?

How to correctly set POST request parameters so that servlet actually receives them?

推荐答案

尝试一下:

        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("IDToken1", "username"));
        nvps.add(new BasicNameValuePair("IDToken2", "password"));

        httPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

这篇关于Apache HTTP客户端,POST请求.如何正确设置请求参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆