convenient for code write

Java http post 代码(传递数据,使用Body传递)


作用:使用java发起post请求,附带data于请求的Body中(非kv参数)

实例:模拟curl功能,可以将某些依托curl完成的数据库数据插入指令转换为java实现

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
public static void http_post(String url, String port, String path, String content) {
/**
* @Description: ingest a address and send the content to it.
* @Example http://localhost:8428/write + content
* @param url url address
* @param port remote address port
* @param path remote address path
* @param content metric data
*/
String result = "";
try {
url = url + ":" + port + "/" + path;
System.out.println(url);
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
conn.setDoInput(true);

// fill and send content
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.write(content.getBytes());
dos.flush();

// get response (Do not comment this line, or the data insertion will be failed)
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println(result);//
} catch (Exception e) {
System.out.println("Exception," + e.getMessage());
e.printStackTrace();
}
}
2020-06-09

⬆︎UP