Apache HTTP Client, POST request. How to correctly set request parameters?

后端 未结 3 841
失恋的感觉
失恋的感觉 2021-01-04 12:30

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 HttpServletR

相关标签:
3条回答
  • 2021-01-04 13:00

    try this:

            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 讨论(0)
  • 2021-01-04 13:04

    You can also use this approach in case you want to pass some http parameters and send a json request:

    (note: I have added in some extra code just incase it helps any other future readers)

    note: imports are from org.apache.http libraries

    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();
    }
    
    0 讨论(0)
  • 2021-01-04 13:15

    Set "Content-Type" header to "application/x-www-form-urlencoded"

    0 讨论(0)
提交回复
热议问题