10 java rest http apache-httpclient-4.x
我正在编写一些使用Apache HttpClient
版本4.2.2
来访问RESTful第三方API的Java代码.该API具有利用HTTP方法GET
,POST
,PUT
和DELETE
.重要的是要注意我使用的是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)
所以我试图找出如何提供HttpClient
与api_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)
如果您想传递一些 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)
归档时间: |
|
查看次数: |
53264 次 |
最近记录: |