REST API Bad Request 문제

public String callAjax(String method, String request) {
String output = “”;
try {
StringEntity strAccessData = new StringEntity("{“Authorization”:"" + request + “”}");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(method);

         strAccessData.setContentType("application/json; charset=UTF-8");
         postRequest.setEntity(strAccessData);

         HttpResponse response = httpClient.execute(postRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
	 throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }
		
   BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()), "UTF-8"));
   StringBuilder sb = new StringBuilder("");
		
   while ((output = br.readLine()) != null) {
	sb.append(output);
    }
    output = sb.toString();
		
    httpClient.getConnectionManager().shutdown();

} catch (Exception e) {
		
}

return output;
}

method = https://kapi.kakao.com/v1/user/signup
request = Bearer {access_token}

response 가
HTTP/1.1 400 Bad Request [Date: Tue, 16 Jan 2018 08:40:40 GMT, Server: Apache, Content-Type: application/json;charset=UTF-8, Content-Length: 60, Connection: close] 라고 출력됩니다.

request 가 어떻게 잘못되었는지 알고싶습니다.

자답입니다

content-type이 application/x-www-form-urlencoded; charset=utf-8로 되어야 한다는 글을 봤는데

Entity에 Authorization=Bearer {access_token}을 넣고 httpClient.execute(postRequest);

하면 되는게 아닌가요?ㅜㅜ

계속 같은 결과가 나오네요.

Content-Type도 변하지가 않습니다

@hyo0978
respnse header의 content-type은 application/json;charset=UTF-8 이 맞습니다.
request header의 content-type이 application/x-www-form-urlencoded; charset=utf-8 이어야 하구요.
response body도 한번 찍어보시겠어요?
body에 원인이 내려가니 한번 확인해보세요.

response를 아래의 코드로 찍어보았습니다.

HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, “UTF-8”);
logger.info(“responseString----->”+responseString);

responseString ----> {“msg”:“access token should not be null or empty”,“code”:-2} 라고 나오네요…

값이 set된것까지 확인했습니다

@hyo0978

{"msg":"access token should not be null or empty","code":-2}

헤더 값이 제대로 전달되지 못했네요. 아래 코드를 참고하세요.

postRequest.setHeader("Accept", "application/json");
postRequest.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
postRequest.setHeader("Authorization", "Bearer {access token}");

감사합니다.
문제 해결하였습니다.

  1. 헤더에 Accept 를 추가하고

  2. application/x-www-form-urlencoded;charset=utf-8이라
    key, value를 key=value로 넣으려고 했었는데

말씀주신것 처럼 수정해서 해결했습니다.
감합니다.

1개의 좋아요