原生方式
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* 客户端工具类
*/
public class HttpClient {
/**
* 向指定URL发送POST请求
*
* @param url
* @param heads
* @param body
* @return 响应结果
*/
public static Map<String, Object> sendPost(String url, Map<String, String> heads, Map<String, String> body) {
PrintWriter out = null;
BufferedReader in = null;
String res = "";
Map<String, Object> value = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
if (heads != null) {//设置头信息
for (Map.Entry<String, String> header : heads.entrySet()) {
conn.setRequestProperty(header.getKey(), header.getValue());
}
}
conn.setRequestProperty("Charset", "UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
//获取响应头信息
out = new PrintWriter(conn.getOutputStream());
// 设置请求属性
String param = "";
if (body != null && body.size() > 0) {
Iterator<String> ite = body.keySet().iterator();
while (ite.hasNext()) {
String key = ite.next();// key
String val = body.get(key);
param += key + "=" + val + "&";
}
param = param.substring(0, param.length() - 1);
}
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
res += line;
}
Map head = conn.getHeaderFields();
Set<String> keys = head.keySet();
JSONObject headData = new JSONObject();
for (String key : keys) {
headData.put(key, conn.getHeaderField(key));
}
JSONObject jsonObject = JSONObject.parseObject(res, JSONObject.class);
JSONObject bodyData = new JSONObject();
bodyData.put(ServerConsts.code, jsonObject.getInteger(ServerConsts.code));
bodyData.put(ServerConsts.reason, jsonObject.getString(ServerConsts.reason));
bodyData.put(ServerConsts.result, jsonObject.getString(ServerConsts.result));
value = new HashMap<>();
value.put(ServerConsts.head, headData);
value.put(ServerConsts.body, bodyData);
} catch (Exception e) {
e.printStackTrace();
System.err.println("发送 POST 请求出现异常!" + e.getMessage());
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return value;
}
public static void main(String[] args) {
Map<String, String> head = new HashMap<>();
head.put("asd", "asd");
head.put("asd", "dsa");
String pathUrl = "http://192.168.241.1:81/v2.0";
Map<String, String> body = new HashMap<>();
body.put("asd", "afdffs");
Map<String, Object> stringMapMap = HttpClient.sendPost(pathUrl, head, body);
for (Map.Entry<String, Object> stringObjectEntry : stringMapMap.entrySet()) {
System.out.println(stringObjectEntry.getKey() + "::" + stringObjectEntry.getValue());
}
}
}
封装方式 (get与post)
pom.xml坐标
这里使用了fastjson依赖,使用json作为参数进行数据传输,如果有特殊需求可以不引入fastdfs依赖,修改传输传递的代码即可
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
代码
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.Map;
/**
* http发送工具类
*/
public class HttpUtil {
public static String sendPost(String url, JSONObject headJson, JSONObject bodyJson) throws Exception {
CloseableHttpClient client = null;
String result = null;
try {
client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);//支持get/post与put和delete - > HttpDelete
if (headJson != null) {//设置请求头
for (Map.Entry<String, Object> head : headJson.entrySet()) {
post.addHeader(head.getKey(), head.getValue().toString());
}
}
StringEntity body = new StringEntity(bodyJson.toJSONString(), "utf-8");//设置请求体
body.setContentEncoding("UTF-8");
body.setContentType("application/json");//设置发送的请求体数据为json数据
post.setEntity(body);
HttpResponse res = client.execute(post);
result = EntityUtils.toString(res.getEntity());// 返回json格式:
} catch (Exception e) {
throw new Exception(e);
} finally {
close(client);
}
return result;
}
public static String sendGet(String url, JSONObject headJson) throws Exception {
String result = null;
CloseableHttpClient client = null;
try {
client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(url);
if (headJson != null) {//设置请求头
for (Map.Entry<String, Object> entry : headJson.entrySet()) {
get.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
}
}
HttpResponse res = client.execute(get);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(res.getEntity());// 返回json格式:
}
} catch (Exception e) {
throw new Exception(e);
} finally {
close(client);
}
return result;
}
/**
* 关闭资源
*
* @param client
*/
public static void close(CloseableHttpClient client) {
if (client != null) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
JSONObject bodyJson = new JSONObject();
bodyJson.put("key1", "value1");
bodyJson.put("key2", "value2");
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("key1", "value1");
jsonObject1.put("key2", "value2");
jsonObject1.put("key3", "value3");
bodyJson.put("key3", jsonObject1);
String resp = HttpUtil.sendPost("http://127.0.0.1:8080", null, bodyJson);
System.out.println("服务端的响应为: " + resp);
}
}