1、主要使用对象:
HttpClient:客户端
HttpGet 和 HttpPost:两种请求
RequestConfig:请求配置
HttpResponse:请求返回体
2、一般使用方法
创建客户端
配置客户端参数
创建get 或post 请求
设置请求参数如:添加cookie,请求头
执行请求,得到HttpResponse对象
解析HttpResponse,获取需要数据
下面将所有的操作放在一个自己写的工具类中:
public class NetRequest {
HttpClient client;
HttpGet get;
HttpPost post;
HttpResponse response;
boolean isGet = false;
boolean isPost = false;
public NetRequest() {
client = HttpClientBuilder.create().build();
}
/**
* 设置Get 请求
* @param url
* @param params
* @return
*/
public NetRequest setGet(String url,Map<String, Object> params){
if(isPost){
client = HttpClientBuilder.create().build();
}
URI uri = setURI(url, params);
get = new HttpGet(uri);
isGet = true;
isPost = false;
return this;
}
/**
* 设置Post请求
* @param url
* @param params
* @return
*/
public NetRequest setPost(String url,Map<String, Object> params){
if(isGet){
client = HttpClientBuilder.create().build();
}
URI uri = setURI(url, null);
HttpEntity entity = setEntity(params);
post = new HttpPost(uri);
post.setEntity(entity);
isGet = false;
isPost = true;
return this;
}
/**
* 添加请求头
* @param name
* @param value
* @return
*/
public NetRequest addHead(String name,String value){
if(isGet){
get.addHeader(name, value);
}
if(isPost){
post.addHeader(name, value);
}
return this;
}
/**
* 添加Cookie
* @param cookie
* @return
*/
public NetRequest addCookie(String cookie){
addHead("Cookie", cookie);
return this;
}
/**
* 设置请求配置
* @param config
* @return
*/
public NetRequest setRequestConfig(RequestConfig config){
if(isGet){
get.setConfig(config);
}
if(isPost){
post.setConfig(config);
}
return this;
}
/**
* 设置请求超时
* @param conTime 连接
* @param socketTime 数据传输
* @return
*/
public NetRequest setConnectiontime(int conTime,int socketTime){
RequestConfig config = RequestConfig.custom().setConnectTimeout(conTime).setSocketTimeout(socketTime).build();
return setRequestConfig(config);
}
/**
* 执行请求
* @return
*/
public NetRequest doRequest(){
//response = null;
try{
if(isGet){
response = client.execute(get);
}
if(isPost){
response = client.execute(post);
}
}catch(Exception e){
e.printStackTrace();
}
return this;
}
/**
* 获取返回字符串
* @return
*/
public String getStr(){
try{
HttpEntity entity = response.getEntity();
String body = EntityUtils. toString(entity);
return body;
} catch(Exception e){
e.printStackTrace();
return null;
}
}
public HttpResponse getResponse(){
return response;
}
/**
* 下载文件
* @param file
* @return
*/
public File getFile(File file){
try{
InputStream inputStream = response.getEntity().getContent();
OutputStream outputStream = new FileOutputStream(file);
int index = 0;
byte[] btys = new byte[4096];
while(( index = inputStream.read( btys)) != -1){
outputStream.write( btys, 0, index);
}
inputStream.close();
outputStream.flush();
outputStream.close();
return file;
} catch(Exception e){
return null;
}
}
public File getFile(String filePath){
try{
File file = new File( filePath);
if(! file.exists()){
if(! file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
file.createNewFile();
}
return getFile(file);
} catch(Exception e){
e.printStackTrace();
return null;
}
}
/**
* 设置参数 --在URI中
* @param url
* @param params
* @return
*/
public static URI setURI(String url,Map<String, Object> params){
try{
if(! url.startsWith( "http")){
url = "http://" + url;
}
URIBuilder builder = new URIBuilder( url);
if( params == null){
return builder.build();
}
Set<String> keys = params.keySet();
for (String key : keys) {
Object object = params.get( key);
if( object.getClass().equals(File. class)){
} else{
builder.addParameter( key, object.toString());
}
}
return builder.build();
} catch(Exception e){
e.printStackTrace();
return null;
}
}
/**
* 设置参数 --包含文件上传
* @param params
* @return
*/
public static HttpEntity setEntity(Map<String, Object> params){
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode. BROWSER_COMPATIBLE);//浏览器兼容模式
try{
builder.setCharset(CharsetUtils. get("UTF-8" )); //设置编码
} catch(Exception e){
}
Set<String> keys = params.keySet();
for (String key : keys) {
Object object = params.get( key);
if(object == null )
continue;
if( object.getClass().equals(File. class)){
FileBody fileBody = new FileBody((File) object);
builder.addPart( key, fileBody);
} else if(object.getClass().equals(String.class)){
StringBody stringBody = new StringBody(object.toString(), ContentType.TEXT_PLAIN);
builder.addPart( key, stringBody);
}
}
return builder.build();
}
}
测试用例:
NetRequest netRequest = new NetRequest();
String sign = baseUrl + "/sign/mysign?page=1&step=1000&type=1";
JSONArray array = JSONArray.parseArray(netRequest.setGet(sign, null).addCookie("JSESSIONID=9A5611188E3E25193DF1F848A012957D").doRequest().getStr());