获取第三方数据,第三方给的接口是form表单形式,当时找了很多种方法都不太行,如果遇到第三方访问时候是一下代码这种情况时候:
Request request = new Request(taskConfig.getUrl());
request.setMethod(HttpConstant.Method.POST);
request.addHeader("accessToken", ”accessToken值”);
Map<String, Object> param = new HashMap<>(10);
param.put(“A”, 值);
param.put(“B”, 值);
request.setRequestBody(HttpRequestBody.form(param, Charsets.UTF_8.name()));
return request;
可以使用这段代码进行访问对方接口,完成业务处理:
String url = "url";
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(1000);
connManager.setDefaultMaxPerRoute(1000);
CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connManager)
.setConnectionManagerShared(true).build();
HttpPost httpPost = new HttpPost(url);// 创建httpPost
HashMap<String, String> header = new HashMap<>();
httpPost.setHeader("accessToken", "accessToken值");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(20000)
.setSocketTimeout(20000).setConnectTimeout(20000).build();
httpPost.setConfig(requestConfig);
//设置参数
String params = "A=值&B=值【from表单请求参数】";
StringEntity entity = new StringEntity(params, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(entity);
CloseableHttpResponse response = null;
try
{
response = httpclient.execute(httpPost);
StatusLine status = response.getStatusLine();
int state = status.getStatusCode();
if (state == HttpStatus.SC_OK)
{
HttpEntity responseEntity = response.getEntity();
//结果转为字符串
String jsonString = EntityUtils.toString(responseEntity, "UTF-8");
if (jsonString != null)
{
if (jsonString != "")
{
业务处理
}
}
}
}
finally
{
if (response != null)
{
try
{
response.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
//需要拼接循环请求将注释下方部分代码进行外提。
try
{
httpclient.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return success;