Java 发送http请求(get、post)的示例
1.情景展示
java发送get请求、post请求(form表单、json数据)至另一服务器;
可设置HTTP请求头部信息,可以接收服务器返回cookie信息,可以上传文件等;
2.代码实现
所需jar包:httpcore-4.4.1.jar;httpclient-4.4.1.jar;httpmime-4.4.1.jar;epoint-utils-9.3.3.jar
importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importjava.nio.charset.Charset;
importjava.security.GeneralSecurityException;
importjava.security.cert.CertificateException;
importjava.security.cert.X509Certificate;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
importjavax.net.ssl.HostnameVerifier;
importjavax.net.ssl.SSLContext;
importjavax.net.ssl.SSLSession;
importorg.apache.http.Header;
importorg.apache.http.HttpEntity;
importorg.apache.http.HttpResponse;
importorg.apache.http.NameValuePair;
importorg.apache.http.client.config.RequestConfig;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.CloseableHttpResponse;
importorg.apache.http.client.methods.HttpDelete;
importorg.apache.http.client.methods.HttpEntityEnclosingRequestBase;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.client.methods.HttpPatch;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.client.methods.HttpRequestBase;
importorg.apache.http.conn.ssl.SSLConnectionSocketFactory;
importorg.apache.http.conn.ssl.TrustStrategy;
importorg.apache.http.entity.ContentType;
importorg.apache.http.entity.StringEntity;
importorg.apache.http.entity.mime.MultipartEntityBuilder;
importorg.apache.http.entity.mime.content.StringBody;
importorg.apache.http.impl.client.CloseableHttpClient;
importorg.apache.http.impl.client.HttpClients;
importorg.apache.http.impl.conn.PoolingHttpClientConnectionManager;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.ssl.SSLContextBuilder;
importorg.apache.http.util.EntityUtils;
importcom.epoint.core.utils.string.StringUtil;
/**
*HttpClient工具类,使用http-client包实现,原先的common-httpclient已经淘汰
*
*@作者ko
*@version[版本号,2017年10月18日]
*/
publicclassHttpUtil
{
privatestaticPoolingHttpClientConnectionManagerconnMgr;
privatestaticRequestConfigrequestConfig;
privatestaticfinalintMAX_TIMEOUT=7000;
/**
*直接以流返回
*/
publicstaticfinalintRTN_TYPE_1=1;
/**
*直接以string返回
*/
publicstaticfinalintRTN_TYPE_2=2;
/**
*以map返回,reslut:接口结果string;statusCode:http状态码
*/
publicstaticfinalintRTN_TYPE_3=3;
/**
*以map返回,reslut:接口结果string;statusCode:http状态码;cookie:response的cookie
*cookie值键值对,格式key1=value1;key2=value2;...
*/
publicstaticfinalintRTN_TYPE_4=4;
/**
*默认上传文件的文件流或file的keyName
*/
privatestaticfinalStringDEFAULT_BINARYBODY_KEYNAME="file";
static{
//设置连接池
connMgr=newPoolingHttpClientConnectionManager();
//设置连接池大小
connMgr.setMaxTotal(100);
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
//在提交请求之前测试连接是否可用
connMgr.setValidateAfterInactivity(1);
RequestConfig.BuilderconfigBuilder=RequestConfig.custom();
//设置连接超时
configBuilder.setConnectTimeout(MAX_TIMEOUT);
//设置读取超时
configBuilder.setSocketTimeout(MAX_TIMEOUT);
//设置从连接池获取连接实例的超时
configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
requestConfig=configBuilder.build();
}
/**
*发送GET请求
*
*@paramapiUrl
* API接口URL
*@returnString响应内容
*/
publicstaticStringdoGet(StringapiUrl){
returndoHttp(apiUrl,null,"get",RTN_TYPE_2);
}
/**
*发送POST请求
*
*@paramapiUrl
* API接口URL
*@paramparams
* K-V参数
*@returnString响应内容
*/
publicstaticStringdoPost(StringapiUrl,Mapparams){
returndoHttp(apiUrl,params,"post",RTN_TYPE_2);
}
/**
*发送POST请求
*
*@paramapiUrl
* API接口URL
*@paramjson
* json参数
*@returnString响应内容
*/
publicstaticStringdoPostJson(StringapiUrl,Stringjson){
returndoHttp(apiUrl,json,"post",RTN_TYPE_2);
}
/**
*发送http请求
*
*@paramapiUrl
* API接口URL
*@paramparams
* {MapK-V形式、json字符串}
*@parammethod
* {null、或者post:POST请求、patch:PATCH请求、delete:DELETE请求、get:GET请求}
*@paramtype
* {HttpUtil.RTN_TYPE_1:请求返回stream(此时流需要在外部手动关闭);HttpUtil.
* RTN_TYPE_2:string;HttpUtil.RTN_TYPE_3:返回一个map,map包含结果(
* 结果是string形式)以及http状态码;HttpUtil.RTN_TYPE_4:返回一个map,map包含结果(
* 结果是string形式),http状态码和cookie;其他情况返回string}
* 如果结果是个map,key为:result,statusCode,cookie,分别返回结果
* string,http状态码,cookie;cookie值键值对,格式
* key1=value1;key2=value2;...
*@returnstream或string或map
*/
publicstaticTdoHttp(StringapiUrl,Objectparams,Stringmethod,inttype){
returndoHttp(apiUrl,null,params,method,type);
}
/**
*发送http请求
*
*@paramapiUrl
* API接口URL
*@paramheaderMap
* header信息Map,可设置cookie
*@paramparams
* {MapK-V形式、json字符串}
*@parammethod
* {null、或者post:POST请求、patch:PATCH请求、delete:DELETE请求、get:GET请求}
*@paramtype
* {HttpUtil.RTN_TYPE_1:请求返回stream(此时流需要在外部手动关闭);HttpUtil.
* RTN_TYPE_2:string;HttpUtil.RTN_TYPE_3:返回一个map,map包含结果(
* 结果是string形式)以及http状态码;HttpUtil.RTN_TYPE_4:返回一个map,map包含结果(
* 结果是string形式),http状态码和cookie;其他情况返回string}
* 如果结果是个map,key为:result,statusCode,cookie,分别返回结果
* string,http状态码,cookie;cookie值键值对,格式
* key1=value1;key2=value2;...
*@returnstream或string或map
*/
publicstaticTdoHttp(StringapiUrl,MapheaderMap,Objectparams,Stringmethod,inttype){
CloseableHttpClienthttpClient=null;
if(isSSL(apiUrl)){
httpClient=HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
}
else{
httpClient=HttpClients.createDefault();
}
returndoHttp(httpClient,apiUrl,headerMap,params,method,type);
}
/**
*发送http请求
*
*@paramhttpClient
* httpclient对象由外部传入,用户需要保持登录状态等情况此时如果要ssl,那么要在外部加入ssl特性
* httpClient=
* HttpClients.custom().setSSLSocketFactory(HttpUtil.
* createSSLConnSocketFactory())
* .setConnectionManager(HttpUtil.getConnMgr()).
* setDefaultRequestConfig(HttpUtil..getRequestConfig()).build();
*@paramapiUrl
* API接口URL
*@paramheaderMap
* header信息Map,可设置cookie
*
*@paramparams
* {MapK-V形式、json字符串}
*@parammethod
* {null、或者post:POST请求、patch:PATCH请求、delete:DELETE请求、get:GET请求}
*@paramtype
* {HttpUtil.RTN_TYPE_1:请求返回stream(此时流需要在外部手动关闭);HttpUtil.
* RTN_TYPE_2:string;HttpUtil.RTN_TYPE_3:返回一个map,map包含结果(
* 结果是string形式)以及http状态码;HttpUtil.RTN_TYPE_4:返回一个map,map包含结果(
* 结果是string形式),http状态码和cookie;其他情况返回string}
* 如果结果是个map,key为:result,statusCode,cookie,分别返回结果
* string,http状态码,cookie;cookie值键值对,格式
* key1=value1;key2=value2;...
*@returnstream或string或map
*/
@SuppressWarnings("unchecked")
publicstaticTdoHttp(CloseableHttpClienthttpClient,StringapiUrl,MapheaderMap,
Objectparams,Stringmethod,inttype){
HttpRequestBasehttpPost=null;
if(StringUtil.isNotBlank(method)){
if("patch".equalsIgnoreCase(method)){
httpPost=newHttpPatch(apiUrl);
}
elseif("delete".equalsIgnoreCase(method)){
httpPost=newHttpDelete(apiUrl);
}
elseif("get".equalsIgnoreCase(method)){
httpPost=newHttpGet(apiUrl);
}
elseif("post".equalsIgnoreCase(method)){
httpPost=newHttpPost(apiUrl);
}
}
else{
httpPost=newHttpPost(apiUrl);
}
CloseableHttpResponseresponse=null;
try{
//设置header信息
if(headerMap!=null&&!headerMap.isEmpty()){
for(Map.Entryentry:headerMap.entrySet()){
httpPost.addHeader(entry.getKey(),entry.getValue());
}
}
if(isSSL(apiUrl)){
httpPost.setConfig(requestConfig);
}
//参数不为null、要处理参数
if(params!=null){
//get请求拼接在url后面
if(httpPostinstanceofHttpGet){
StringBufferparam=newStringBuffer();
if(paramsinstanceofMap){
MapparamsConvert=(Map)params;
inti=0;
for(Stringkey:paramsConvert.keySet()){
if(i==0)
param.append("?");
else
param.append("&");
param.append(key).append("=").append(paramsConvert.get(key));
i++;
}
}
else{
param.append("?"+params.toString());
}
apiUrl+=param;
}
//delete请求暂不处理
elseif(!(httpPostinstanceofHttpDelete)){
//K-V形式
if(paramsinstanceofMap){
MapparamsConvert=(Map)params;
ListpairList=newArrayList<>(paramsConvert.size());
for(Map.Entryentry:paramsConvert.entrySet()){
NameValuePairpair=newBasicNameValuePair(entry.getKey(),
entry.getValue()==null?"":entry.getValue().toString());
pairList.add(pair);
}
((HttpEntityEnclosingRequestBase)httpPost)
.setEntity(newUrlEncodedFormEntity(pairList,Charset.forName("UTF-8")));
}
//json格式
else{
StringEntitystringEntity=newStringEntity(params.toString(),"UTF-8");
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
((HttpEntityEnclosingRequestBase)httpPost).setEntity(stringEntity);
}
}
}
response=httpClient.execute(httpPost);
//intstatusCode=response.getStatusLine().getStatusCode();
//if(statusCode!=HttpStatus.SC_OK){
//returnnull;
//}
HttpEntityentity=response.getEntity();
if(entity!=null){
if(type==RTN_TYPE_1){
return(T)entity.getContent();
}
elseif(RTN_TYPE_2==type){
return(T)EntityUtils.toString(entity,"UTF-8");
}
elseif(RTN_TYPE_3==type||RTN_TYPE_4==type){
MaprtnMap=newHashMap();
rtnMap.put("result",EntityUtils.toString(entity,"UTF-8"));
rtnMap.put("statusCode",response.getStatusLine().getStatusCode()+"");
if(RTN_TYPE_4==type){
rtnMap.put("cookie",getCookie(response));
}
return(T)rtnMap;
}
else{
return(T)EntityUtils.toString(entity,"UTF-8");
}
}
}
catch(Exceptione){
e.printStackTrace();
}
finally{
if(response!=null&&type!=RTN_TYPE_1){
try{
EntityUtils.consume(response.getEntity());
}
catch(IOExceptione){
e.printStackTrace();
}
}
}
returnnull;
}
/**
*上传附件(post形式)
*
*@paramurl
* 请求地址
*@paramheaderMap
* header参数mapMap
*@paramparamMap
* 额外的参数map,Map
*@paramfile
* 可以选择本地文件上传;如果传了file,又传了fileName,那么文件名以fileName为准,否则是file的文件名
*@paramfileName
* 以流传输时,必须指定文件名
*@paramssl
* 是否需要ssl
*@returnresult,返回上传结果,如果接口没有返回值,则为状态码
*/
publicstaticStringupload(Stringurl,MapheaderMap,MapparamMap,Filefile,
StringfileName,booleanssl){
returnupload(url,headerMap,paramMap,file,null,fileName,ssl);
}
/**
*上传附件(post形式)
*
*@paramurl
* 请求地址
*@paramheaderMap
* header参数mapMap
*@paramparamMap
* 额外的参数map,Map
*@paramin
* 文件流
*@paramfileName
* 以流传输时,必须指定文件名
*@paramssl
* 是否需要ssl
*@returnresult,返回上传结果,如果接口没有返回值,则为状态码
*/
publicstaticStringupload(Stringurl,MapheaderMap,MapparamMap,InputStreamin,
StringfileName,booleanssl){
returnupload(url,headerMap,paramMap,null,in,fileName,ssl);
}
/**
*上传附件(post形式)
*
*@paramhttpClient
* 外部传入httpClient
*@paramurl
* 请求地址
*@paramheaderMap
* header参数mapMap
*@paramparamMap
* 额外的参数map,Map
*@paramfile
* 可以选择本地文件上传;如果传了file,又传了fileName,那么文件名以fileName为准,否则是file的文件名
*@paramfileName
* 以流传输时,必须指定文件名
*@paramssl
* 是否需要ssl
*@returnresult,返回上传结果,如果接口没有返回值,则为状态码
*/
publicstaticStringupload(CloseableHttpClienthttpClient,Stringurl,MapheaderMap,
MapparamMap,Filefile,StringfileName,booleanssl){
returnupload(httpClient,url,headerMap,paramMap,file,null,fileName,ssl);
}
/**
*上传附件(post形式)
*
*@paramhttpClient
* 外部传入httpClient
*@paramurl
* 请求地址
*@paramheaderMap
* header参数mapMap
*@paramparamMap
* 额外的参数map,Map
*@paramin
* 文件流
*@paramfileName
* 以流传输时,必须指定文件名
*@paramssl
* 是否需要ssl
*@returnresult,返回上传结果,如果接口没有返回值,则为状态码
*/
publicstaticStringupload(CloseableHttpClienthttpClient,Stringurl,MapheaderMap,
MapparamMap,InputStreamin,StringfileName,booleanssl){
returnupload(httpClient,url,headerMap,paramMap,null,in,fileName,ssl);
}
/**
*上传附件(post形式)
*
*@paramurl
* 请求地址
*@paramheaderMap
* header参数mapMap
*@paramparamMap
* 额外的参数map,Map
*@paramfile
* 可以选择本地文件上传,file,in互斥;如果传了file,又传了fileName,那么文件名以fileName为准,否则
* 是file的文件名
*@paramin
* 文件流
*@paramfileName
* 以流传输时,必须指定文件名
*@paramssl
* 是否需要ssl
*@returnresult,返回上传结果,如果接口没有返回值,则为状态码
*/
privatestaticStringupload(Stringurl,MapheaderMap,MapparamMap,Filefile,
InputStreamin,StringfileName,booleanssl){
CloseableHttpClienthttpClient=null;
if(ssl){
httpClient=HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
}
else{
httpClient=HttpClients.createDefault();
}
returnupload(httpClient,url,headerMap,paramMap,file,in,fileName,ssl);
}
/**
*上传附件(post形式)
*
*@paramhttpClient
* 外部传入httpClient
*@paramurl
* 请求地址
*@paramheaderMap
* header参数mapMap
*@paramparamMap
* 额外的参数map,Map
*@paramfile
* 可以选择本地文件上传,file,in互斥;如果传了file,又传了fileName,那么文件名以fileName为准,否则
* 是file的文件名
*@paramin
* 文件流
*@paramfileName
* 以流传输时,必须指定文件名
*@paramssl
* 是否需要ssl
*@returnresult,返回上传结果,如果接口没有返回值,则为状态码
*/
privatestaticStringupload(CloseableHttpClienthttpClient,Stringurl,MapheaderMap,
MapparamMap,Filefile,InputStreamin,StringfileName,booleanssl){
Stringresult="";
CloseableHttpResponseresponse=null;
try{
HttpPosthttpPost=newHttpPost(url);
//设置header信息
if(headerMap!=null&&!headerMap.isEmpty()){
for(Map.Entryentry:headerMap.entrySet()){
httpPost.addHeader(entry.getKey(),entry.getValue());
}
}
if(ssl){
httpPost.setConfig(requestConfig);
}
MultipartEntityBuilderbuilder=MultipartEntityBuilder.create();
//选择以file形式上传
if(file!=null&&file.exists()){
if(StringUtil.isNotBlank(fileName)){
builder.addBinaryBody(DEFAULT_BINARYBODY_KEYNAME,file,ContentType.DEFAULT_BINARY,fileName);
}
else{
builder.addBinaryBody(DEFAULT_BINARYBODY_KEYNAME,file);
}
}
//以流上传
elseif(in!=null&&StringUtil.isNotBlank(fileName)){
builder.addBinaryBody(DEFAULT_BINARYBODY_KEYNAME,in,ContentType.DEFAULT_BINARY,fileName);
}
if(paramMap!=null&&!paramMap.isEmpty()){
for(Map.Entryentry:paramMap.entrySet()){
builder.addPart(entry.getKey(),newStringBody(entry.getValue(),ContentType.TEXT_PLAIN));
}
}
HttpEntityreqEntity=builder.build();
httpPost.setEntity(reqEntity);
response=httpClient.execute(httpPost);
HttpEntityentity=response.getEntity();
if(entity!=null){
result=EntityUtils.toString(entity,"UTF-8");
}
else{
result=response.getStatusLine().getStatusCode()+"";
}
}
catch(Exceptione){
e.printStackTrace();
}
finally{
if(response!=null){
try{
EntityUtils.consume(response.getEntity());
}
catch(IOExceptione){
e.printStackTrace();
}
}
}
returnresult;
}
privatestaticStringgetCookie(HttpResponsehttpResponse){
MapcookieMap=newHashMap(64);
Headerheaders[]=httpResponse.getHeaders("Set-Cookie");
if(headers==null||headers.length==0){
returnnull;
}
Stringcookie="";
for(inti=0;i
以上就是Java发送http请求(get、post)的示例的详细内容,更多关于Java发送http请求的资料请关注毛票票其它相关文章!