我照网上教程写了一个HttpClient工厂 GET数据是正常可以使用的(不需要设置参数) 但是传入新数据无法使用(需要设置参数)
我的工厂是这样的 execute后面url是请求地址 setParams 后面的Params 是需要传入的参数
传入新数据的实现方法是
package com.zr0701.Http;
import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpClientPostNewData extends AbstractHttpClient{
private String body;
@Override
public String execute(String url) {
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
try {
httpClient = HttpClients.createDefault();
//请求配置
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000)
.setConnectTimeout(20000)
.build();
//创建HttpPost实例
httpPost = new HttpPost(url);
//对HttpPost指定配置
httpPost.setConfig(requestConfig);
//传入的参数,传入的参数类型为"APPLICATION_JSON"
StringEntity requestEntity = new StringEntity(body, ContentType.APPLICATION_JSON);
/* UrlEncodedFormEntity requestEntity = new UrlEncodedFormEntity(ps);*/
httpPost.setEntity(requestEntity);
//启动httpPost请求
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String reponseInformation = EntityUtils.toString(entity,"UTF-8");
return reponseInformation;
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (httpPost != null) {
httpPost.releaseConnection();
}
if (httpClient != null ) {
httpClient.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
@Override
public AbstractHttpClient setParams(Object params) {
Gson gson = new Gson();
body = gson.toJson(params);
return this;
}
}
我在 外部是这样调用工厂的
运行的时候发现没有返回值
然后断点测试发现这段代码并不能跳入 我的Http工厂
我的GET方法是可以正常跳入的 并且可以获得数据