第一个版本(含字符串数组):
相关依赖:
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
发送方:
package com.tm.demo.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
/**
* @Classname HttpTest
* @Description TODO 测试http请求工具类
* @Date 2019/7/3 0003 16:24
* @Created by jtj
*/
public class HttpTest {
public static void main(String[] args) throws Exception {
Map<String,String> map = new HashMap<>();
//参数是字符串类型
map.put("msgType", "0"); //消息类型
map.put("cmdId","1"); //指令标识
//参数有数组,转成json字符串
Map<String,String[]> cmdParams = new HashMap<>();
cmdParams.put("dev", new String[]{"1","2","3"});
map.put("cmdParams",JSONObject.toJSONString(cmdParams)); //指令参数
//发送请求
String result = postMethod("http://localhost:8080/test", map);
System.out.println("返回结果:"+result);
}
/**
* @param url 请求地址
* @param params 参数
* @return 结果
* @throws Exception
*/
public static String postMethod(String url, Map<String, String> params) throws Exception {
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = null;
RequestConfig config = RequestConfig.custom().setConnectTimeout(20000).setSocketTimeout(20000).build();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(config);
List<NameValuePair> list = new ArrayList<NameValuePair>();
Set<String> keySets = params.keySet();
for (String key : keySets) {
String value = params.get(key);
list.add(new BasicNameValuePair(key, value));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(list));
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
return content;
} catch (Exception e) {
throw e;
} finally {
httpPost.releaseConnection();
response.close();
}
}
}
接收方:
@RequestMapping("/test")
@ResponseBody
public String test(HttpServletRequest request){
Map<String,String[]> params = request.getParameterMap();
Iterator entries = params.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, String[]> entry = (Map.Entry<String, String[]>)entries.next();
//获取key值
System.out.println("Key = " + entry.getKey());
//这里的value值为数组形式,暂时用字符串代替,按自己需要去组织
System.out.println("Value = " + JSONObject.toJSONString(entry.getValue()));
}
return "copy";
}
第二版本(不含字符串数组):
package com.swft.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
/**
* @ClassName: HttpObject
* @description:
* @author: JTJ
* @Date: 2019年2月18日 下午5:49:55
*/
public class HttpObject {
/**
* @Title: sendPost
* @Desc: 向指定url发送post请求
* @param url 指定url地址
* @param params 请求参数
* @return 远程资源的响应结果
*/
public String sendPost(String url, Map<String, String> params) {
OutputStreamWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
URL realUrl = new URL(url);
HttpURLConnection conn =(HttpURLConnection) realUrl.openConnection();
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// POST方法
conn.setRequestMethod("POST");
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.connect();
// 获取URLConnection对象对应的输出流
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
// 发送请求参数
if (params != null) {
StringBuilder param = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if(param.length()>0){
param.append("&");
}
param.append(entry.getKey());
param.append("=");
param.append(entry.getValue());
//System.out.println(entry.getKey()+":"+entry.getValue());
}
//System.out.println("param:"+param.toString());
out.write(param.toString());
}
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result.toString();
}
}