안녕하세요. 자바에서 REST API를 활용하여 나에게 보내기 기능을 구현해 보고 있습니다.
JSONObject jsonl = new JSONObject();
jsonl.put("web_url", "https://developers.kakao.com");
jsonl.put("mobile_web_url", "https://developers.kakao.com");
JSONObject jsonm = new JSONObject();
jsonm.put("object_type", "text");
jsonm.put("text", text);
jsonm.put("link", jsonl);
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("template_object", jsonm);
sendPush(map);
필수로 필요한 키인 object_type, text, link를 만들어서 보냅니다.
public String mapToJsonStr(MultiValueMap<String, String> map) throws JsonProcessingException {
return JACKSON_OBJECT_MAPPER.writeValueAsString(map);
// return GSON.toJson(map);
}
public static String mapToParams(MultiValueMap<String, Object> map) {
StringBuilder paramBuilder = new StringBuilder();
for (String key : map.keySet()) {
System.out.println(key+" "+map.get(key));
paramBuilder.append(paramBuilder.length() > 0 ? "&" : "");
paramBuilder.append(String.format("%s=%s", urlEncodeUTF8(key),
urlEncodeUTF8(map.get(key).toString())));
}
return paramBuilder.toString();
}
public static String sendPush(final MultiValueMap<String, Object> map) {
return request(HttpMethodType.POST, PUSH_SEND_PATH, mapToParams(map));
}
public static String request(HttpMethodType httpMethod, final String apiPath, final String params) {
String requestUrl = API_SERVER_HOST + apiPath;
if (httpMethod == null) {
httpMethod = HttpMethodType.GET;
}
if (params != null && params.length() > 0
&& (httpMethod == HttpMethodType.GET || httpMethod == HttpMethodType.DELETE)) {
requestUrl += params;
}
HttpsURLConnection conn;
OutputStreamWriter writer = null;
BufferedReader reader = null;
InputStreamReader isr = null;
try {
final URL url = new URL(requestUrl);
conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod(httpMethod.toString());
conn.setRequestProperty("Authorization", "Bearer " + KAKAO_TOKEN);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
if (params != null && params.length() > 0 && httpMethod == HttpMethodType.POST) {
conn.setDoOutput(true);
writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(params);
writer.flush();
}
final int responseCode = conn.getResponseCode();
System.out.println(String.format("\nSending '%s' request to URL : %s", httpMethod, requestUrl));
System.out.println("Response Code : " + responseCode);
if (responseCode == 200)
isr = new InputStreamReader(conn.getInputStream());
else
isr = new InputStreamReader(conn.getErrorStream());
reader = new BufferedReader(isr);
final StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
System.out.println(buffer.toString());
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) try { writer.close(); } catch (Exception ignore) { }
if (reader != null) try { reader.close(); } catch (Exception ignore) { }
if (isr != null) try { isr.close(); } catch (Exception ignore) { }
}
return null;
}
public static String urlEncodeUTF8(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new UnsupportedOperationException(e);
}
}
그 다음 과정은 Java로 REST API 호출 샘플 코드 게시물을 참고하였습니다.
오류는 다음과 같습니다.
template_object [{“object_type”:“text”,“link”:{“web_url”:“https://developers.kakao.com”,“mobile_web_url”:“https://developers.kakao.com”},“text”:“16282”}] //이건 제가 프린트해본 것 입니다.
Sending ‘POST’ request to URL : https://kapi.kakao.com/v2/api/talk/memo/default/send
Response Code : 400
{“msg”:“failed to parse parameter. name=template_object, stringToParse=-, paramString=-, paramStringAlias=null”,“code”:-2}
제 생각엔 파라미터 파싱이 제대로 이루어지지 않았다고 생각하는데 어떻게 바꿔야 할지 모르겠습니다. 검색도 많이 해봤는데 도저히 모르겠습니다. 답변해 주시면 정말 감사하겠습니다.