详解java实现HTTP请求的三种方式
目前JAVA实现HTTP请求的方法用的最多的有两种:一种是通过HTTPClient这种第三方的开源框架去实现。HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,HttpClient3.1是org.apache.commons.httpclient下操作远程url的工具包,虽然已不再更新,但实现工作中使用httpClient3.1的代码还是很多,HttpClient4.5是org.apache.http.client下操作远程url的工具包,最新的;另一种则是通过HttpURLConnection去实现,HttpURLConnection是JAVA的标准类,是JAVA比较原生的一种实现方式。
自己在工作中三种方式都用到过,总结一下分享给大家,也方便自己以后使用,话不多说上代码。
第一种方式:java原生HttpURLConnection
packagecom.powerX.httpClient;
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
importjava.net.HttpURLConnection;
importjava.net.MalformedURLException;
importjava.net.URL;
publicclassHttpClient{
publicstaticStringdoGet(Stringhttpurl){
HttpURLConnectionconnection=null;
InputStreamis=null;
BufferedReaderbr=null;
Stringresult=null;//返回结果字符串
try{
//创建远程url连接对象
URLurl=newURL(httpurl);
//通过远程url连接对象打开一个连接,强转成httpURLConnection类
connection=(HttpURLConnection)url.openConnection();
//设置连接方式:get
connection.setRequestMethod("GET");
//设置连接主机服务器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
//设置读取远程返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
//发送请求
connection.connect();
//通过connection连接,获取输入流
if(connection.getResponseCode()==200){
is=connection.getInputStream();
//封装输入流is,并指定字符集
br=newBufferedReader(newInputStreamReader(is,"UTF-8"));
//存放数据
StringBuffersbf=newStringBuffer();
Stringtemp=null;
while((temp=br.readLine())!=null){
sbf.append(temp);
sbf.append("\r\n");
}
result=sbf.toString();
}
}catch(MalformedURLExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
//关闭资源
if(null!=br){
try{
br.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=is){
try{
is.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
connection.disconnect();//关闭远程连接
}
returnresult;
}
publicstaticStringdoPost(StringhttpUrl,Stringparam){
HttpURLConnectionconnection=null;
InputStreamis=null;
OutputStreamos=null;
BufferedReaderbr=null;
Stringresult=null;
try{
URLurl=newURL(httpUrl);
//通过远程url连接对象打开连接
connection=(HttpURLConnection)url.openConnection();
//设置连接请求方式
connection.setRequestMethod("POST");
//设置连接主机服务器超时时间:15000毫秒
connection.setConnectTimeout(15000);
//设置读取主机服务器返回数据超时时间:60000毫秒
connection.setReadTimeout(60000);
//默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
connection.setDoOutput(true);
//默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
connection.setDoInput(true);
//设置传入参数的格式:请求参数应该是name1=value1&name2=value2的形式。
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
//设置鉴权信息:Authorization:Bearerda3efcbf-0845-4fe3-8aba-ee040be542c0
connection.setRequestProperty("Authorization","Bearerda3efcbf-0845-4fe3-8aba-ee040be542c0");
//通过连接对象获取一个输出流
os=connection.getOutputStream();
//通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
os.write(param.getBytes());
//通过连接对象获取一个输入流,向远程读取
if(connection.getResponseCode()==200){
is=connection.getInputStream();
//对输入流对象进行包装:charset根据工作项目组的要求来设置
br=newBufferedReader(newInputStreamReader(is,"UTF-8"));
StringBuffersbf=newStringBuffer();
Stringtemp=null;
//循环遍历一行一行读取数据
while((temp=br.readLine())!=null){
sbf.append(temp);
sbf.append("\r\n");
}
result=sbf.toString();
}
}catch(MalformedURLExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
//关闭资源
if(null!=br){
try{
br.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=os){
try{
os.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=is){
try{
is.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
//断开与远程地址url的连接
connection.disconnect();
}
returnresult;
}
}
第二种方式:apacheHttpClient3.1
packagecom.powerX.httpClient;
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.UnsupportedEncodingException;
importjava.util.Iterator;
importjava.util.Map;
importjava.util.Map.Entry;
importjava.util.Set;
importorg.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
importorg.apache.commons.httpclient.HttpClient;
importorg.apache.commons.httpclient.HttpStatus;
importorg.apache.commons.httpclient.NameValuePair;
importorg.apache.commons.httpclient.methods.GetMethod;
importorg.apache.commons.httpclient.methods.PostMethod;
importorg.apache.commons.httpclient.params.HttpMethodParams;
publicclassHttpClient3{
publicstaticStringdoGet(Stringurl){
//输入流
InputStreamis=null;
BufferedReaderbr=null;
Stringresult=null;
//创建httpClient实例
HttpClienthttpClient=newHttpClient();
//设置http连接主机服务超时时间:15000毫秒
//先获取连接管理器对象,再获取参数对象,再进行参数的赋值
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
//创建一个Get方法实例对象
GetMethodgetMethod=newGetMethod(url);
//设置get请求超时为60000毫秒
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,60000);
//设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,newDefaultHttpMethodRetryHandler(3,true));
try{
//执行Get方法
intstatusCode=httpClient.executeMethod(getMethod);
//判断返回码
if(statusCode!=HttpStatus.SC_OK){
//如果状态码返回的不是ok,说明失败了,打印错误信息
System.err.println("Methodfaild:"+getMethod.getStatusLine());
}else{
//通过getMethod实例,获取远程的一个输入流
is=getMethod.getResponseBodyAsStream();
//包装输入流
br=newBufferedReader(newInputStreamReader(is,"UTF-8"));
StringBuffersbf=newStringBuffer();
//读取封装的输入流
Stringtemp=null;
while((temp=br.readLine())!=null){
sbf.append(temp).append("\r\n");
}
result=sbf.toString();
}
}catch(IOExceptione){
e.printStackTrace();
}finally{
//关闭资源
if(null!=br){
try{
br.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=is){
try{
is.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
//释放连接
getMethod.releaseConnection();
}
returnresult;
}
publicstaticStringdoPost(Stringurl,MapparamMap){
//获取输入流
InputStreamis=null;
BufferedReaderbr=null;
Stringresult=null;
//创建httpClient实例对象
HttpClienthttpClient=newHttpClient();
//设置httpClient连接主机服务器超时时间:15000毫秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
//创建post请求方法实例对象
PostMethodpostMethod=newPostMethod(url);
//设置post请求超时时间
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,60000);
NameValuePair[]nvp=null;
//判断参数map集合paramMap是否为空
if(null!=paramMap&¶mMap.size()>0){//不为空
//创建键值参数对象数组,大小为参数的个数
nvp=newNameValuePair[paramMap.size()];
//循环遍历参数集合map
Set>entrySet=paramMap.entrySet();
//获取迭代器
Iterator>iterator=entrySet.iterator();
intindex=0;
while(iterator.hasNext()){
EntrymapEntry=iterator.next();
//从mapEntry中获取key和value创建键值对象存放到数组中
try{
nvp[index]=newNameValuePair(mapEntry.getKey(),
newString(mapEntry.getValue().toString().getBytes("UTF-8"),"UTF-8"));
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
}
index++;
}
}
//判断nvp数组是否为空
if(null!=nvp&&nvp.length>0){
//将参数存放到requestBody对象中
postMethod.setRequestBody(nvp);
}
//执行POST方法
try{
intstatusCode=httpClient.executeMethod(postMethod);
//判断是否成功
if(statusCode!=HttpStatus.SC_OK){
System.err.println("Methodfaild:"+postMethod.getStatusLine());
}
//获取远程返回的数据
is=postMethod.getResponseBodyAsStream();
//封装输入流
br=newBufferedReader(newInputStreamReader(is,"UTF-8"));
StringBuffersbf=newStringBuffer();
Stringtemp=null;
while((temp=br.readLine())!=null){
sbf.append(temp).append("\r\n");
}
result=sbf.toString();
}catch(IOExceptione){
e.printStackTrace();
}finally{
//关闭资源
if(null!=br){
try{
br.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=is){
try{
is.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
//释放连接
postMethod.releaseConnection();
}
returnresult;
}
}
第三种方式:apache httpClient4.5
packagecom.powerX.httpClient;
importjava.io.IOException;
importjava.io.UnsupportedEncodingException;
importjava.util.ArrayList;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importjava.util.Map.Entry;
importjava.util.Set;
importorg.apache.http.HttpEntity;
importorg.apache.http.NameValuePair;
importorg.apache.http.client.ClientProtocolException;
importorg.apache.http.client.config.RequestConfig;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.CloseableHttpResponse;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.impl.client.CloseableHttpClient;
importorg.apache.http.impl.client.HttpClients;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.util.EntityUtils;
publicclassHttpClient4{
publicstaticStringdoGet(Stringurl){
CloseableHttpClienthttpClient=null;
CloseableHttpResponseresponse=null;
Stringresult="";
try{
//通过址默认配置创建一个httpClient实例
httpClient=HttpClients.createDefault();
//创建httpGet远程连接实例
HttpGethttpGet=newHttpGet(url);
//设置请求头信息,鉴权
httpGet.setHeader("Authorization","Bearerda3efcbf-0845-4fe3-8aba-ee040be542c0");
//设置配置请求参数
RequestConfigrequestConfig=RequestConfig.custom().setConnectTimeout(35000)//连接主机服务超时时间
.setConnectionRequestTimeout(35000)//请求超时时间
.setSocketTimeout(60000)//数据读取超时时间
.build();
//为httpGet实例设置配置
httpGet.setConfig(requestConfig);
//执行get请求得到返回对象
response=httpClient.execute(httpGet);
//通过返回对象获取返回数据
HttpEntityentity=response.getEntity();
//通过EntityUtils中的toString方法将结果转换为字符串
result=EntityUtils.toString(entity);
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
//关闭资源
if(null!=response){
try{
response.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=httpClient){
try{
httpClient.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
returnresult;
}
publicstaticStringdoPost(Stringurl,MapparamMap){
CloseableHttpClienthttpClient=null;
CloseableHttpResponsehttpResponse=null;
Stringresult="";
//创建httpClient实例
httpClient=HttpClients.createDefault();
//创建httpPost远程连接实例
HttpPosthttpPost=newHttpPost(url);
//配置请求参数实例
RequestConfigrequestConfig=RequestConfig.custom().setConnectTimeout(35000)//设置连接主机服务超时时间
.setConnectionRequestTimeout(35000)//设置连接请求超时时间
.setSocketTimeout(60000)//设置读取数据连接超时时间
.build();
//为httpPost实例设置配置
httpPost.setConfig(requestConfig);
//设置请求头
httpPost.addHeader("Content-Type","application/x-www-form-urlencoded");
//封装post请求参数
if(null!=paramMap&¶mMap.size()>0){
Listnvps=newArrayList();
//通过map集成entrySet方法获取entity
Set>entrySet=paramMap.entrySet();
//循环遍历,获取迭代器
Iterator>iterator=entrySet.iterator();
while(iterator.hasNext()){
EntrymapEntry=iterator.next();
nvps.add(newBasicNameValuePair(mapEntry.getKey(),mapEntry.getValue().toString()));
}
//为httpPost设置封装好的请求参数
try{
httpPost.setEntity(newUrlEncodedFormEntity(nvps,"UTF-8"));
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
}
}
try{
//httpClient对象执行post请求,并返回响应参数对象
httpResponse=httpClient.execute(httpPost);
//从响应对象中获取响应内容
HttpEntityentity=httpResponse.getEntity();
result=EntityUtils.toString(entity);
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
//关闭资源
if(null!=httpResponse){
try{
httpResponse.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=httpClient){
try{
httpClient.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
returnresult;
}
}
有时候我们在使用post请求时,可能传入的参数是json或者其他格式,此时我们则需要更改请求头及参数的设置信息,以httpClient4.5为例,更改下面两列配置:httpPost.setEntity(newStringEntity("你的json串")); httpPost.addHeader("Content-Type","application/json")。
以上所述是小编给大家介绍的java实现HTTP请求的三种方式详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!