Java发送http请求

前言

项目上有时候需要发送http请求并获取返回的Json结果,这里记录下请求和接受返回的方法。

使用Java自带方法发送http请求

  • 参数:
    • 请求地址:url e.g. http://192.168.1.107:7777/api/test;
    • 参数:bodys 键值对Map对象;
    • 请求头:headers 键值对Map对象;
    • 方法名:method e.g. POST/PUT;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
*
* @param url
* @param bodys
* @param headers
* @param method
* @return
* @throws IOException
*/
public static String sendPostRequest(String url, Map<String,String> bodys,Map<String,String> headers,String method) throws IOException {
StringBuilder builder = new StringBuilder();
Set<Map.Entry<String,String>> entrys = null;
if(bodys!=null && !bodys.isEmpty()){
entrys = bodys.entrySet();
for (Map.Entry<String, String> entry : entrys) {
builder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue()==null?"":entry.getValue(),"UTF-8")).append("&");
}
builder.deleteCharAt(builder.length() - 1);
}
URL _url = new URL(url);
HttpURLConnection con = (HttpURLConnection)_url.openConnection();
if(headers!=null && !headers.isEmpty()){
entrys = headers.entrySet();
for (Map.Entry<String, String> entry : entrys) {
con.setRequestProperty(entry.getKey(),entry.getValue());
}
}
con.setRequestMethod(method);
con.setDoOutput(true);
con.setDoInput(true);
OutputStream os = con.getOutputStream();
os.write(builder.toString().getBytes("UTF-8"));
os.flush();
os.close();

String str = "";
if(con.getResponseCode() == 200){
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
str = reader.readLine();
}
return str;
}
-------------本文结束感谢您的阅读-------------