1. Form values 전달
@Test
public void postTemplate() {
String response = null;
try {
String urlPath = "https://webhook.site/{your_unique_url}";
URL url = new URL(urlPath);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
String param = "param1=a";
param += "¶m2=b";
param += "¶m3=c";
param += "¶m4=d";
OutputStream os = con.getOutputStream();
os.write(param.getBytes("utf-8"));
os.flush();
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "euc-kr"));
StringBuffer sb = new StringBuffer();
String inputLine;
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
br.close();
response = sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(response);
}
- https://webhook.site/를 통해 전송결과 확인
2. JSON 전달
- pom.xml json-simple dependency 추가
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
public void postJSONTemplate() {
String response = null;
try {
String urlPath = "https://webhook.site/{your_unique_url}";
URL url = new URL(urlPath);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-type", "application/json");
con.setDoOutput(true);
JSONObject jsonObject = new JSONObject();
jsonObject.put("param1", "a");
jsonObject.put("param2", "b");
jsonObject.put("param3", "c");
OutputStream os = con.getOutputStream();
os.write(jsonObject.toString().getBytes("utf-8"));
os.flush();
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "euc-kr"));
StringBuffer sb = new StringBuffer();
String inputLine;
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
br.close();
response = sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(response);
}
- https://webhook.site/를 통해 전송결과 확인
'JAVA' 카테고리의 다른 글
[알고리즘] 비트연산 (0) | 2021.07.21 |
---|---|
[Regex] 정규 표현식 (0) | 2021.07.16 |