Apache HTTP Client,POST请求。如何正确设置请求参数?

时间:2011-08-15 17:30:44

标签: post httpclient

我正在使用Apache HTTP Client,我需要向我的servlet发送POST请求。 发送请求时,我的servlet没有收到任何参数(在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实际接收它们?

3 个答案:

答案 0 :(得分:21)

试试这个:

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

答案 1 :(得分:1)

设置&#34;内容类型&#34;标题为&#34; application / x-www-form-urlencoded&#34;

答案 2 :(得分:0)

如果您想传递一些http参数并发送json请求,也可以使用此方法:

(注意:我添加了一些额外的代码,只是为了帮助其他未来的读者)

注意:导入来自org.apache.http库

public void postJsonWithHttpParams() throws URISyntaxException, UnsupportedEncodingException, IOException {

    //add the http parameters you wish to pass
    List<NameValuePair> postParameters = new ArrayList<>();
    postParameters.add(new BasicNameValuePair("param1", "param1_value"));
    postParameters.add(new BasicNameValuePair("param2", "param2_value"));

    //Build the server URI together with the parameters you wish to pass
    URIBuilder uriBuilder = new URIBuilder("http://google.ug");
    uriBuilder.addParameters(postParameters);

    HttpPost postRequest = new HttpPost(uriBuilder.build());
    postRequest.setHeader("Content-Type", "application/json");

    //this is your JSON string you are sending as a request
    String yourJsonString = "{\"str1\":\"a value\",\"str2\":\"another value\"} ";

    //pass the json string request in the entity
    HttpEntity entity = new ByteArrayEntity(yourJsonString.getBytes("UTF-8"));
    postRequest.setEntity(entity);

    //create a socketfactory in order to use an http connection manager
    PlainConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
    Registry<ConnectionSocketFactory> connSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", plainSocketFactory)
            .build();

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(connSocketFactoryRegistry);

    connManager.setMaxTotal(20);
    connManager.setDefaultMaxPerRoute(20);

    RequestConfig defaultRequestConfig = RequestConfig.custom()
            .setSocketTimeout(HttpClientPool.connTimeout)
            .setConnectTimeout(HttpClientPool.connTimeout)
            .setConnectionRequestTimeout(HttpClientPool.readTimeout)
            .build();

    // Build the http client.
    CloseableHttpClient httpclient = HttpClients.custom()
            .setConnectionManager(connManager)
            .setDefaultRequestConfig(defaultRequestConfig)
            .build();

    CloseableHttpResponse response = httpclient.execute(postRequest);

    //Read the response
    String responseString = "";

    int statusCode = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();

    HttpEntity responseHttpEntity = response.getEntity();

    InputStream content = responseHttpEntity.getContent();

    BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
    String line;

    while ((line = buffer.readLine()) != null) {
        responseString += line;
    }

    //release all resources held by the responseHttpEntity
    EntityUtils.consume(responseHttpEntity);

    //close the stream
    response.close();

    // Close the connection manager.
    connManager.close();
}