如何向所有HttpClient请求方法添加参数?

10 java rest http apache-httpclient-4.x

我正在编写一些使用Apache HttpClient版本4.2.2来访问RESTful第三方API的Java代码.该API具有利用HTTP方法GET,POST,PUTDELETE.重要的是要注意我使用的是4.xx版本,而不是3.xx,因为API从3变为4.我发现的所有相关示例都是针对3.xx版本.

所有API调用需要您提供api_key参数(regardles哪种方法你正在使用).这意味着关于我是否正在进行GET,POST或其他方式,我需要提供此信息api_key以便对服务器端进行身份验证.

// Have to figure out a way to get this into my HttpClient call,
// regardless of whether I'm using: HttpGet, HttpPost, HttpPut
// or HttpDelete...
String api_key = "blah-whatever-my-unique-api-key";
Run Code Online (Sandbox Code Playgroud)

所以我试图找出如何提供HttpClientapi_key不顾我的请求方法(而这又取决于它的RESTful API方法,我试图打).它看起来HttpGet甚至不支持参数的概念,并HttpPost使用一些叫做的东西HttpParams; 但这些HttpParams似乎只存在于3.xx版本中HttpClient.

所以我问:什么是正确的,v4.2.2方式将我的api_key字符串附加/添加到所有四个:

  • HttpGet
  • HttpPost
  • HttpPut
  • HttpDelete

提前致谢.

Rag*_*lly 26

您可以使用URIBuilder类为所有HTTP方法构建请求URI.URI构建器提供setParameter方法来设置参数.

URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("www.google.com").setPath("/search")
    .setParameter("q", "httpclient")
    .setParameter("btnG", "Google Search")
    .setParameter("aq", "f")
    .setParameter("oq", "");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
Run Code Online (Sandbox Code Playgroud)

输出应该是

http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq= 
Run Code Online (Sandbox Code Playgroud)

  • 谢谢@rboorgapally(+1) - 但是我相信这只适用于`HttpGet`(在查询字符串上设置参数),对于`HttpPost`,`HttpPut`或`HttpDelete`没有任何影响.虽然每个都有一个构造函数接受一个`URI`作为参数,我不相信`URIBuilder`隐含地知道将查询字符串参数转换为,例如,`HttpPost` POST变量等等.所以虽然我会通过非-HttpGet`方法使用完整的查询字符串来处理URI,我不相信他们会知道如何将该查询字符串转换为他们知道如何使用的数据格式. (4认同)
  • 您是否尝试将带有参数的`URI`对象传递给`HttpPost`?你能检查它是否自动设置`URI`对象的参数? (2认同)

Art*_*hur 5

如果您想传递一些 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();
}
Run Code Online (Sandbox Code Playgroud)