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

2022-09-04 05:50:43

我正在编写一些使用Apache版本的Java代码来访问RESTful 3rd派对API。此 API 具有利用 HTTP 、 和 .重要的是要注意,我使用的是4.x.x版本而不是3.x.x版本,因为API从3到4发生了很大变化。我找到的所有相关示例都是针对3.x.x版本的。HttpClient4.2.2GETPOSTPUTDELETE

所有 API 调用都要求您提供 as 参数(无论您使用哪种方法)。这意味着无论我是进行GET,POST还是其他方式,我都需要提供此信息,以便调用对服务器端进行身份验证。api_keyapi_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";

因此,我正在尝试弄清楚如何提供不考虑我的请求方法(这又取决于我尝试使用哪种RESTful API方法)。它看起来甚至不支持参数的概念,并使用一种叫做;但同样,这些似乎只存在于 3.x.x 版本的 .HttpClientapi_keyHttpGetHttpPostHttpParamsHttpParamsHttpClient

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

  • HttpGet
  • HttpPost
  • HttpPut
  • HttpDelete

提前致谢。


答案 1

可以使用 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());

输出应为

http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq= 

答案 2

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

推荐