一、HttpClient发送请求
导入apache的httpclient jar包
1.1通过CloseableHttpClient发送xml格式参数的post请求
/**
* 通过CloseableHttpClient发送xml格式参数的post请求
* @param url
* @param xmlString
* @return
*/
public static String sendXmlPost(String url,String xmlString){
//1.创建httpclient工具对象
CloseableHttpClient client = HttpClients.createDefault();
//2.创建post请求方法
HttpPost post = new HttpPost(url);
// 构建请求配置信息(可选)
RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) // 创建连接的最长时间
.setConnectionRequestTimeout(500) // 从连接池中获取到连接的最长时间
.setSocketTimeout(10 * 1000) // 数据传输的最长时间
.build();
post.setConfig(config);
CloseableHttpResponse response = null;
String resultMsg = null;
try{
//设置请求头部类型
post.setHeader("Content-Type","text/xml;charset=UTF-8");
//设置请求体
StringEntity xmlEntity = new StringEntity(xmlString,Consts.UTF_8);
post.setEntity(xmlEntity);
//执行
response = client.execute(post);
//如果只有状态码返回,设置返回数据为状态码
if(response.getStatusLine().getStatusCode() == 200){
resultMsg = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
}
return resultMsg;
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if(client!=null){
client.close();
}
if(response != null){
response.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
1.2发送json格式字符串的请求
/**
* 发送json格式字符串的请求
* @param url
* @param json
* @return
*/
public static String sendJsonPost(String url,String json){
//1.创建httpclient工具对象
CloseableHttpClient client = HttpClients.createDefault();
//2.创建post请求方法
HttpPost post = new HttpPost(url);
CloseableHttpResponse response = null;
String resultMsg = null;
try{
//设置请求头部类型
post.setHeader("Content-Type","application/json;charset=UTF-8");
//设置请求体
StringEntity jsonEntity = new StringEntity(json,Consts.UTF_8);
post.setEntity(jsonEntity);
//执行
response = client.execute(post);
//如果只有状态码返回,设置返回数据为状态码
if(response.getStatusLine().getStatusCode() == 200){
resultMsg = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
}
return resultMsg;
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if(client!=null){
client.close();
}
if(response != null){
response.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
1.3通过httpclient模拟表单发送请求
/**
* 通过httpclient模拟表单发送请求
* @param url
* @param map
* @return
*/
public static String sendFormPost(String url,Map map){
//1.创建httpclient工具对象
CloseableHttpClient client = HttpClients.createDefault();
//2.创建post请求方法
HttpPost post = new HttpPost(url);
//封装参数
List parameters = new ArrayList();
for(Map.Entry entry:map.entrySet()){
parameters.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
// 构造一个form表单式的实体
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,Consts.UTF_8);
CloseableHttpResponse response = null;
String resultMsg = null;
try{
//设置请求头部类型
post.setHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
//设置请求体
post.setEntity(formEntity);
//执行
response = client.execute(post);
//如果只有状态码返回,设置返回数据为状态码
if(response.getStatusLine().getStatusCode() == 200){
resultMsg = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
}
return resultMsg;
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if(client!=null){
client.close();
}
if(response != null){
response.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
1.4通过httpclient模拟表单发送请求
public static String sendGet() throws URISyntaxException{
//1.创建httpclient工具对象
CloseableHttpClient client = HttpClients.createDefault();
HttpGet get = new HttpGet(new URIBuilder("http://localhost:8080/xxxxxx/get").setParameter("wd", "java").build());
CloseableHttpResponse response = null;
String resultMsg = null;
try {
// 执行请求
response = client.execute(get);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultMsg = EntityUtils.toString(response.getEntity(), "UTF-8");
}
return resultMsg;
}catch(Exception e){
e.printStackTrace();
}finally {
try {
if(client!=null){
client.close();
}
if(response != null){
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
二、java内置的URL工具类发送请求
2.1java的URL发送JSON数据请求
public static String sendPost(String url, String param) {
OutputStreamWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);// 向连接中写入数据
conn.setDoInput(true);// 从连接中读取数据
//conn.setInstanceFollowRedirects(true);//自动执行HTTP重定向
conn.setUseCaches(false);//Post请求不能使用缓存
// 设置请求方式为POST方法
conn.setRequestMethod("POST");
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.connect();
// 获取URLConnection对象对应的输出流
out = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
// 发送请求参数,发送的数据在此处发送。
out.write(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line ;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
2.2java的URL发送xml数据请求
//java的URL发送xml数据请求
public static String sendXml(String url, String param) {
OutputStreamWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);// 向连接中写入数据
conn.setDoInput(true);// 从连接中读取数据
//conn.setInstanceFollowRedirects(true);//自动执行HTTP重定向
conn.setUseCaches(false);//Post请求不能使用缓存
// 设置请求方式为POST方法
conn.setRequestMethod("POST");
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
conn.connect();
// 获取URLConnection对象对应的输出流
out = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
// 发送请求参数,发送的数据在此处发送。
out.write(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line ;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
2.3java的URL模拟form表单发送数据
//java的URL模拟form表单发送数据
public static String urlForm(String url, Map map) {
URL u = null;
HttpURLConnection con = null;
// 构建请求参数
StringBuffer sb = new StringBuffer();
if (map != null) {
for (Map.Entry e : map.entrySet()) {
sb.append(e.getKey());
sb.append("=");
sb.append(e.getValue());
sb.append("&");
}
sb.substring(0, sb.length() - 1);
}
System.out.println("send_url:" + url);
System.out.println("send_data:" + sb.toString());
// 尝试发送请求
try {
u = new URL(url);
con = (HttpURLConnection) u.openConnection();
POST 只能为大写,严格限制,post会不识别
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
osw.write(sb.toString());
osw.flush();
osw.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.disconnect();
}
}
// 读取返回内容
StringBuffer buffer = new StringBuffer();
try {
//一定要有返回值,否则无法把请求发送给server端。
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String temp;
while ((temp = br.readLine()) != null) {
buffer.append(temp);
}
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString();
}
2.4java的URL发送get数据请求
//java的URL发送xml数据请求
public static String sendGet(String url) {
OutputStreamWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);// 向连接中写入数据
conn.setDoInput(true);// 从连接中读取数据
//conn.setInstanceFollowRedirects(true);//自动执行HTTP重定向
conn.setUseCaches(false);//Post请求不能使用缓存
// 设置请求方式为POST方法
conn.setRequestMethod("GET");
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.connect();
// 获取URLConnection对象对应的输出流
out = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line ;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}