2011-08-15 9 views
11

私はApache HTTP Clientを使用しており、私のサーブレットにPOSTリクエストを送信する必要があります。 要求が送信されると、私のサーブレットはパラメータを受け取りません(HttpServletRequest)。ここでApache HTTPクライアント、POST要求。リクエストパラメータを正しく設定するには?

は、クライアントプログラムのコードです:

// 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リクエストのパラメータを設定する方法は?

答えて

20

これを試してみてください。また、あなたは、いくつかを渡したい場合には、このアプローチを使用することができます

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

POSTですか? –

+0

これは機能します!しかし、なぜ他のもの(BasicHttpParams)が動作しないのか分からなかった。任意のアイデア/ –

+0

Works :)注目すべき点は、 'UrlEncodedFormEntity'のエンコーディングを指定しなかった場合、Spring Controllerはパラメータを受け取らなかったことです。エンコーディングが実際に必須であるように見えます。 – MJar

1

セット "のContent-Type" ヘッダ "アプリケーション/ x-www-form-urlencodedで" する

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(); 
} 
関連する問題