一、java常见实现http请求模板代码
1、通过JDK网络类Java.net.HttpURLConnection;
2、通过common封装好的HttpClient;
3、通过Apache封装好的CloseableHttpClient;
4、通过SpringBoot-RestTemplate;
5、socket
二、代码
2.1、通过JDK网络类Java.net.HttpURLConnection
比较原始的一种调用做法,这里把get请求和post请求都统一放在一个方法里面。
实现过程:
GET:
1、创建远程连接
2、设置连接方式(get、post、put。。。)
3、设置连接超时时间
4、设置响应读取时间
5、发起请求
6、获取请求数据
7、关闭连接
POST:
1、创建远程连接
2、设置连接方式(get、post、put。。。)
3、设置连接超时时间
4、设置响应读取时间
5、当向远程服务器传送数据/写数据时,需要设置为true(setDoOutput)
6、当前向远程服务读取数据时,设置为true,该参数可有可无(setDoInput)
7、设置传入参数的格式:(setRequestProperty)
8、设置鉴权信息:Authorization:(setRequestProperty)
9、设置参数
10、发起请求
11、获取请求数据
12、关闭连接
直接上代码:
packagecom.riemann.springbootdemo.util.common.httpConnectionUtil;importorg.springframework.lang.Nullable;import java.io.*;importjava.net.HttpURLConnection;importjava.net.MalformedURLException;importjava.net.URL;importjava.net.URLConnection;/***@authorriemann
* @date 2019/05/24 23:42*/
public classHttpURLConnectionUtil {/*** Http get请求
*@paramhttpUrl 连接
*@return响应数据*/
public staticString doGet(String httpUrl){//链接
HttpURLConnection connection = null;
InputStream is= null;
BufferedReader br= null;
StringBuffer result= newStringBuffer();try{//创建连接
URL url = newURL(httpUrl);
connection=(HttpURLConnection) url.openConnection();//设置请求方式
connection.setRequestMethod("GET");//设置连接超时时间
connection.setReadTimeout(15000);//开始连接
connection.connect();//获取响应数据
if (connection.getResponseCode() == 200) {//获取返回的数据
is =connection.getInputStream();if (null !=is) {
br= new BufferedReader(new InputStreamReader(is, "UTF-8"));
String temp= null;while (null != (temp =br.readLine())) {
result.append(temp);
}
}
}
}catch(IOException e) {
e.printStackTrace();
}finally{if (null !=br) {try{
br.close();
}catch(IOException e) {
e.printStackTrace();
}
}if (null !=is) {try{
is.close();
}catch(IOException e) {
e.printStackTrace();
}
}//关闭远程连接
connection.disconnect();
}returnresult.toString();
}/*** Http post请求
*@paramhttpUrl 连接
*@paramparam 参数
*@return
*/
public staticString doPost(String httpUrl, @Nullable String param) {
StringBuffer result= newStringBuffer();//连接
HttpURLConnection connection = null;
OutputStream os= null;
InputStream is= null;
BufferedReader br= null;try{//创建连接对象
URL url = newURL(httpUrl);//创建连接
connection =(HttpURLConnection) url.openConnection();//设置请求方法
connection.setRequestMethod("POST");//设置连接超时时间
connection.setConnectTimeout(15000);//设置读取超时时间
connection.setReadTimeout(15000);//DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个//设置是否可读取
connection.setDoOutput(true);
connection.setDoInput(true);//设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");//拼装参数
if (null != param && param.equals("")) {//设置参数
os =connection.getOutputStream();//拼装参数
os.write(param.getBytes("UTF-8"));
}//设置权限//设置请求头等//开启连接//connection.connect();//读取响应
if (connection.getResponseCode() == 200) {
is=connection.getInputStream();if (null !=is) {
br= new BufferedReader(new InputStreamReader(is, "GBK"));
String temp= null;while (null != (temp =br.readLine())) {
result.append(temp);
result.append("\r\n");
}
}
}
}catch(MalformedURLException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}finally{//关闭连接
if(br!=null){try{
br.close();
}catch(IOException e) {
e.printStackTrace();
}
}if(os!=null){try{
os.close();
}catch(IOException e) {
e.printStackTrace();
}
}if(is!=null){try{
is.close();
}catch(IOException e) {
e.printStackTrace();
}
}//关闭连接
connection.disconnect();
}returnresult.toString();
}public static voidmain(String[] args) {
String message= doPost("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "");
System.out.println(message);
}
}
运行结果:
2.2 通过apache common封装好的HttpClient
httpClient的get或post请求方式步骤:
生成一个HttpClient对象并设置相应的参数;
生成一个GetMethod对象或PostMethod并设置响应的参数;
用HttpClient生成的对象来执行GetMethod生成的Get方法;
处理响应状态码;
若响应正常,处理HTTP响应内容;
释放连接。
httpclinet3.1
导入如下jar包:
commons-httpclient
commons-httpclient
3.1
com.alibaba
fastjson
1.2.32
代码如下:
packagecom.riemann.springbootdemo.util.common.httpConnectionUtil;importcom.alibaba.fastjson.JSONObject;import org.apache.commons.httpclient.*;importorg.apache.commons.httpclient.methods.GetMethod;importorg.apache.commons.httpclient.methods.PostMethod;importorg.apache.commons.httpclient.params.HttpMethodParams;importjava.io.IOException;/***@authorriemann
* @date 2019/05/25 0:58*/
public classHttpClientUtil {/*** httpClient的get请求方式
* 使用GetMethod来访问一个URL对应的网页实现步骤:
* 1.生成一个HttpClient对象并设置相应的参数;
* 2.生