java中的http请求的封装(GET、POST、form表单形式)
⽬前JAVA实现HTTP请求的⽅法⽤的最多的有两种:⼀种是通过HTTPClient这种第三⽅的开源框架去实现。HTTPClient对HTTP的封装性⽐较不错,通过它基本上能够满⾜我
们⼤部分的需求,HttpClient3.1 是 org.apachemons.httpclient下操作远程 url的⼯具包,虽然已不再更新,但实现⼯作中使⽤httpClient3.1的代码还是很多,HttpClient4.5是
org.apache.http.client下操作远程 url的⼯具包,最新的;另⼀种则是通过HttpURLConnection去实现,HttpURLConnection是JAVA的标准类,是JAVA⽐较原⽣的⼀种实现⽅
式。
第⼀种⽅式:java原⽣HttpURLConnection
bile.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import java.io.*;
import java.HttpURLConnection;
import java.MalformedURLException;
import java.URL;
import java.util.*;
public class HttpUtil {
static Logger log = Logger(HttpUtil.class);
/**
* 向指定URL发送GET⽅法的请求
*
* @param httpurl
* 请求参数⽤?拼接在url后边,请求参数应该是 name1=value1&name2=value2 的形式。
* @return result 所代表远程资源的响应结果
*/
public static String doGet(String httpurl) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;// 返回结果字符串
try {
// 创建远程url连接对象
URL url = new URL(httpurl);
/
/ 通过远程url连接对象打开⼀个连接,强转成httpURLConnection类
connection = (HttpURLConnection) url.openConnection();
// 设置连接⽅式:get
connection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
// 发送请求
// 通过connection连接,获取输⼊流
if (ResponseCode() == 200) {
is = InputStream();
// 封装输⼊流is,并指定字符集
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// 存放数据
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = String();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} 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();// 关闭远程连接
}
return result;
}
/**
* 向指定 URL 发送POST⽅法的请求
*
* @param httpUrl
* 发送请求的 URL
* @param param
* 请求参数应该是{"key":"==g43sEvsUcbcunFv3mHkIzlHO4iiUIT R7WwXuSVKTK0yugJnZSlr6q
NbxsL8OqCUAFyCDCoRKQ882m6cTTi0q9uCJsq JJvxS+8mZVRP/7lWfEVt8/N9mKplUA68SWJEPSXyz4MDeFam766KEyvqZ99d"}的形式 * @return所代表远程资源的响应结果
*/
public static String doPost(String httpUrl, String param) {
HttpURLConnection connection = null;
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
String result = null;
try {
URL url = new URL(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/json");
// 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
//connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
// 通过连接对象获取⼀个输出流
os = OutputStream();
// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
os.Bytes());
// 通过连接对象获取⼀个输⼊流,向远程读取
if (ResponseCode() == 200) {
is = InputStream();
// 对输⼊流对象进⾏包装:charset根据⼯作项⽬组的要求来设置
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
// 循环遍历⼀⾏⼀⾏读取数据
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = String();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 断开与远程地址url的连接
connection.disconnect();
}
return result;
}
/
**
*
* @param httpUrl 请求的url
* @param param form表单的参数(key,value形式)
fastjson字符串转数组* @return
*/
public static String doPostForm(String httpUrl, Map param) {
HttpURLConnection connection = null;
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
String result = null;
try {
URL url = new URL(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: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
//connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
// 通过连接对象获取⼀个输出流
os = OutputStream();
// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的(form表单形式的参数实质也是key,value值的拼接,类似于get请求参数的拼接) os.write(createLinkString(param).getBytes());
// 通过连接对象获取⼀个输⼊流,向远程读取
if (ResponseCode() == 200) {
is = InputStream();
// 对输⼊流对象进⾏包装:charset根据⼯作项⽬组的要求来设置
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
// 循环遍历⼀⾏⼀⾏读取数据
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = String();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 断开与远程地址url的连接
connection.disconnect();
}
return result;
}
/**
* 把数组所有元素排序,并按照“参数=参数值”的模式⽤“&”字符拼接成字符串
* @param params 需要排序并参与字符拼接的参数组
* @return拼接后字符串
*/
public static String createLinkString(Map<String, String> params) {
List<String> keys = new ArrayList<String>(params.keySet());
Collections.sort(keys);
StringBuilder prestr = new StringBuilder();
for (int i = 0; i < keys.size(); i++) {
String key = (i);
String value = (key);
if (i == keys.size() - 1) {// 拼接时,不包括最后⼀个&字符
prestr.append(key).append("=").append(value);
} else {
prestr.append(key).append("=").append(value).append("&");
}
}
String();
}
public static void main(String[] args) {
String url = "localhost:8082/api/conf/findConfList?type=1";
String getResult = HttpUtil.doGet(url);
System.out.println(getResult);
url = "localhost:8082/api/core/login";
JSONObject json = new JSONObject();
json.put("key", "==g43sEvsUcbcunFv3mHkIzlHO4iiUIT R7WwXuSVKTK0yugJnZSlr6qNbxsL8OqCUAFyCDCoRKQ882m6cTTi0q9uCJsq JJvxS+8mZVRP/7lWfEVt8/N9mKplUA68SWJEPSXyz4MDeFam766KEyvqZ99d"); String postResult = HttpUtil.doPost(url, JSONString());
System.out.println(postResult);
url = "localhost:8082/api/test/testSendForm";
Map<String,String> map = new HashMap<>();
map.put("name", "测试表单请求");
String formResult = HttpUtil.doPostForm(url, map);
System.out.println(formResult);
}
}
以上包括了get请求和post请求以及form表单请求
第⼆种⽅式:apache HttpClient 3.1
package com.demo.httpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apachemons.httpclient.DefaultHttpMethodRetryHandler;
import org.apachemons.httpclient.HttpClient;
import org.apachemons.httpclient.HttpStatus;
import org.apachemons.httpclient.NameValuePair;
import org.hods.GetMethod;
import org.hods.PostMethod;
import org.apachemons.httpclient.params.HttpMethodParams;
public class HttpClient3 {
public static String doGet(String url) {
// 输⼊流
InputStream is = null;
BufferedReader br = null;
String result = null;
// 创建httpClient实例
HttpClient httpClient = new HttpClient();
/
/ 设置http连接主机服务超时时间:15000毫秒
// 先获取连接管理器对象,再获取参数对象,再进⾏参数的赋值
// 创建⼀个Get⽅法实例对象
GetMethod getMethod = new GetMethod(url);
// 设置get请求超时为60000毫秒
// 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可⽤,false相反
try {
// 执⾏Get⽅法
int statusCode = uteMethod(getMethod);
// 判断返回码
if (statusCode != HttpStatus.SC_OK) {
// 如果状态码返回的不是ok,说明失败了,打印错误信息
} else {
// 通过getMethod实例,获取远程的⼀个输⼊流
is = ResponseBodyAsStream();
// 包装输⼊流
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
/
/ 读取封装的输⼊流
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp).append("\r\n");
}
result = String();
}
} 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();
}
}
// 释放连接
}
return result;
}
public static String doPost(String url, Map<String, Object> paramMap) {
// 获取输⼊流
InputStream is = null;
BufferedReader br = null;
String result = null;
// 创建httpClient实例对象
HttpClient httpClient = new HttpClient();
// 设置httpClient连接主机服务器超时时间:15000毫秒
// 创建post请求⽅法实例对象
PostMethod postMethod = new PostMethod(url);
// 设置post请求超时时间
// 判断参数map集合paramMap是否为空
if (null != paramMap && paramMap.size() > 0) {// 不为空
// 创建键值参数对象数组,⼤⼩为参数的个数
nvp = new NameValuePair[paramMap.size()];
// 循环遍历参数集合map
Set<Entry<String, Object>> entrySet = Set();
// 获取迭代器
Iterator<Entry<String, Object>> iterator = entrySet.iterator();
int index = 0;
while (iterator.hasNext()) {
Entry<String, Object> mapEntry = ();
// 从mapEntry中获取key和value创建键值对象存放到数组中
try {
nvp[index] = new Key(),
new Value().toString().getBytes("UTF-8"), "UTF-8")); } catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
index++;
}
}
// 判断nvp数组是否为空
if (null != nvp && nvp.length > 0) {
// 将参数存放到requestBody对象中
postMethod.setRequestBody(nvp);
}
// 执⾏POST⽅法
try {
int statusCode = uteMethod(postMethod);
// 判断是否成功
if (statusCode != HttpStatus.SC_OK) {
}
// 获取远程返回的数据
is = ResponseBodyAsStream();
/
/ 封装输⼊流
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp).append("\r\n");
}
result = String();
} 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();
}
}
// 释放连接
}
return result;
}
}
第三种⽅式:apache httpClient4.5
bile.utils;
import com.alibaba.fastjson.JSONObject;
import org.apachemons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.fig.RequestConfig;
import org.apache.ity.UrlEncodedFormEntity;
import org.apache.hods.CloseableHttpResponse;
import org.apache.hods.HttpGet;
import org.apache.hods.HttpPost;
import org.ity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.ssage.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import java.io.*;
import java.HttpURLConnection;
import java.MalformedURLException;
import java.URL;
import java.nio.charset.Charset;
import java.util.*;
import java.util.Map.Entry;
public class HttpUtil {
static Logger log = Logger(HttpUtil.class);public static void main(String[] args) {
String url = "localhost:8082/api/conf/findConfList?type=1";
String getResult = Data(url);
System.out.println(getResult);
url = "localhost:8082/api/core/login";
JSONObject json = new JSONObject();
json.put("key", "==g43sEvsUcbcunFv3mHkIzlHO4iiUIT R7WwXuSVKTK0yugJnZSlr6qNbxsL8OqCUAFyCDCoRKQ882m6cTTi0q9uCJsq JJvxS+8mZVRP/7lWfEVt8/N9mKplUA68SWJEPSXyz4MDeFam766KEyvqZ99d"); String postResult = HttpUtil.postData(url, json);
System.out.println(postResult);
url = "localhost:8082/api/test/testSendForm?format=json";
Map<String, Object> map = new HashMap<>();
map.put("name", "测试表单请求");
String formResult = HttpUtil.sendxwwwForm(url, map);
System.out.println(formResult);
}
public static String getData(String url) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
// 通过址默认配置创建⼀个httpClient实例
httpClient = ateDefault();
// 创建httpGet远程连接实例
HttpGet httpGet = new HttpGet(url);
// 设置请求头信息,鉴权
httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
// 设置配置请求参数
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
.setConnectionRequestTimeout(35000)// 请求超时时间
.setSocketTimeout(60000)// 数据读取超时时间
.build();
// 为httpGet实例设置配置
httpGet.setConfig(requestConfig);
// 执⾏get请求得到返回对象
response = ute(httpGet);
// 通过返回对象获取返回数据
HttpEntity entity = Entity();
// 通过EntityUtils中的toString⽅法将结果转换为字符串
result = String(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != response) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
public static String postData(String url, Map<String, Object> paramMap) {
HttpClientBuilder httpClientBuilder = ate();
HttpPost post = new HttpPost(url);
String result = "";
try (CloseableHttpClient closeableHttpClient = httpClientBuilder.build()) {
// HttpEntity entity = new StringEntity(jsonStrData);
// 修复 POST json 导致中⽂乱码
HttpEntity entity = new String(), "UTF-8");
post.setEntity(entity);
post.setHeader("Content-type", "application/json");
HttpResponse resp = ute(post);
try {
InputStream respIs = Entity().getContent();
byte[] respBytes = ByteArray(respIs);
result = new String(respBytes, Charset.forName("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
return result;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论