HttpURLConnection 사용
https://jar-download.com/artifacts/org.json
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class HttpURL {
public static void main(String[] args) throws IOException {
//요청메소드설정
String method = "POST";
//url설정
String url = "https://huqeyhi95c.execute-api.ap-northeast-2.amazonaws.com/prod/start";
//헤더 설정
Map<String,String> headers = new HashMap<>();
headers.put("Content","application/json");
headers.put("Accept","application/json");
headers.put("X-Auth-Token","5dfa6a9da3f3ea4b22164c5a8de648ea");
//파라미터 설정
Map<String, Object> params = new HashMap();
params.put("problem", "1");
//결과받기
JSONObject response = requestJson(method, url,headers,params);
//결과 데이터 사용
String auth_key = (String)response.get("auth_key");
int pr = (Integer) response.get("problem");
int tm = (Integer) response.get("time");
System.out.printf("authKey = %s, pr = %d, tm = %d",auth_key,pr,tm);
}
public static JSONObject requestJson(String method,String urlString,Map<String, String> headers, Map<String, Object> params) throws IOException {
URL url = new URL(urlString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//요청 방식 설정
con.setRequestMethod(method);
//헤더 설정
for(String key:headers.keySet()){
con.setRequestProperty(key,headers.get(key));
}
con.setDoOutput(true);
if(!params.isEmpty()) { //파라미터 맵을 제이슨 오브젝트 형식으로 변경
JSONObject json = new JSONObject(params);
try (OutputStream os = con.getOutputStream()) {
byte[] input = json.toString().getBytes("utf-8");
os.write(input, 0, input.length);
}
}
try (BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
//System.out.println(response.toString());
return new JSONObject(response.toString());
}
}
}
아파치 사용
Download this library as a jar and put it in your libs folder
HttpCore : http://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore/4.4.1
HttpClient : http://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient/4.5
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.commons.logging.LogFactory;
import java.net.URI;
class Test
{
static String x_auth_token="5dfa6a9da3f3ea4b22164c5a8de648ea";
static String baseURL = "https://huqeyhi95c.execute-api.ap-northeast-2.amazonaws.com/prod";
public static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpUriRequest httppost = RequestBuilder.post()
.setUri(new URI(baseURL+"/start"))
.addHeader("X-Auth-Token",x_auth_token)
.addHeader("Content-Type","application/json")
.addParameter("problem", "0")
.build();
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println(EntityUtils.toString(response.getEntity()));
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
'java' 카테고리의 다른 글
java map 순서 유지 (0) | 2022.06.28 |
---|---|
자바 오류 The public type MemberController must be defined in its own file (0) | 2021.11.24 |
awt 한글 깨짐 (0) | 2021.11.07 |
자바에서 "." (점)을 기준으로 split 하기 (0) | 2021.10.23 |
Classpath Dependency Validator Message (0) | 2021.10.02 |