【问题标题】:Apache HTTP Client, POST request. How to correctly set request parameters?Apache HTTP 客户端,POST 请求。如何正确设置请求参数?
【发布时间】:2011-08-15 17:30:44
【问题描述】:

我正在使用 Apache HTTP 客户端,我需要向我的 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真正接收到?

【问题讨论】:

    标签: post httpclient


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 这行得通!但不明白为什么另一个( BasicHttpParams )不起作用。任何想法/
    • Works :) 唯一需要注意的是,当我没有为UrlEncodedFormEntity 指定编码时,Spring Controller 没有收到参数。所以看起来编码实际上是强制性的。
    【解决方案2】:

    将“Content-Type”标头设置为“application/x-www-form-urlencoded”

    【讨论】:

      【解决方案3】:

      如果你想传递一些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();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-18
        • 1970-01-01
        • 2017-03-10
        • 1970-01-01
        • 1970-01-01
        • 2013-01-18
        相关资源
        最近更新 更多