java-HttpURLConnection 发送POST请求 传递参数或JSON数据
需求 三方接口 restful请求 POST方式 参数JSON 接收数据JSON
HttpURLConnection发送POST请求
public class RestUtil {
public String postMethod(String url,String param){
StringBuffer rest=new StringBuffer();
HttpURLConnection conn=null;
OutputStream out=null;
BufferedReader br=null;
try {
URL restUrl = new URL(url);
conn= (HttpURLConnection) restUrl.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection","keep-Alive");
conn.setRequestProperty("Content-Type","application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
out=conn.getOutputStream();
out.write(param.getBytes());
out.flush();
br=new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
String line=null;
while (null != (line=br.readLine())){
rest.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (br!=null) {
br.close();
}
if (out!=null) {
out.close();
}
if (conn!=null) {
conn.disconnect();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return rest.toString();
}
}
客户端请求
@GetMapping("/getData")
public String getData() {
RestUtil restUtil = new RestUtil();
String IP = "127.0.0.1";
String url = "http://" + IP + "/server/data";
String level = "0";
String dateTime = "2020-10";
String param;
String result;
param = "{\"level\":\"" + level + "\",\"dateTime\":\"" + dateTime + "\"}";
result = restUtil.postMethod(url, param);
StringBuffer dataBuffer = new StringBuffer();
try {
dataBuffer.append(URLEncoder.encode("level", "UTF-8"));
dataBuffer.append("=");
dataBuffer.append(URLEncoder.encode(level, "UTF-8"));
dataBuffer.append("&");
dataBuffer.append(URLEncoder.encode("dateTime", "UTF-8"));
dataBuffer.append("=");
dataBuffer.append(URLEncoder.encode(dateTime, "UTF-8"));
param = dataBuffer.toString();
result = restUtil.postMethod(url, param);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println("result==" + result);
JSONObject jsonObject = JSON.parseObject(result);
String code = jsonObject.get("code") == null ? "" : jsonObject.get("code").toString();
String message = jsonObject.get("message") == null ? "" : jsonObject.get("message").toString();
dateTime = jsonObject.get("dateTime") == null ? "" : jsonObject.get("dateTime").toString();
JSONArray dataJsonArray = (JSONArray) jsonObject.get("data");
if (null != dataJsonArray && dataJsonArray.size() > 0) {
for (int i = 0; i < dataJsonArray.size(); i++) {
JSONObject data = (JSONObject) dataJsonArray.get(i);
String account = data.get("account") == null ? "" : data.get("account").toString();
String name = data.get("name") == null ? "" : data.get("name").toString();
System.out.println("code==" + code + "++message==" + message + "++dateTime==" + dateTime
+ "++account==" + account + "++name==" + name);
}
}
return "success";
}
服务端 如果接收为JSON数据的话 就要从流中取出数据
(2021/6/21新增->不建议这种方法,直接参数加注解 @RequestBody)
BufferedReader br=null;
StringBuffer result=null;
try {
br=new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
String line=null;
while (null!=(line=br.readLine())){
result.append(line);
}
System.out.println("接收参数:"+result.toString());
} catch (Exception e) {
e.printStackTrace();
}
服务端 如果是普通参数的话 直接获取
String level = request.getParameter("level");
String dateTime = request.getParameter("dateTime");
服务端返回JSON数据
return "{\"code\":\"100001\",\"message\":\"请求成功\",\"dateTime\":\"2020-10\"," +
"\"data\":[{\"account\":\"zhangsan\",\"name\":\"张三\"}," +
"{\"account\":\"lisi\",\"name\":\"李四\"}," +
"{\"account\":\"wangwu\",\"name\":\"王五\"}," +
"{\"account\":\"xiaoliu\",\"name\":\"小六\"}]}";
推荐使用第三方库
这里使用的是 hutool , 很方便
public static void main(String[] args) {
String getRequestStringUrl = "http://localhost:8080/getRequest?id=1";
HttpRequest.get(getRequestStringUrl).timeout(5 * 60 * 1000).execute();
String postRequestStringUrl = "http://localhost:8080/postRequest";
JSONObject jsonObject = new JSONObject();
jsonObject.put("data","123");
jsonObject.put("email","[email protected]");
Map<String, String > heads = new HashMap<>();
heads.put("Content-Type", "application/json;charset=UTF-8");
HttpRequest.post(postRequestStringUrl)
.headerMap(heads, false)
.body(jsonObject.toJSONString())
.timeout(5 * 60 * 1000)
.execute();
}