Apache HttpClient5를 사용하는 Java 프로그램에서 웹 API를 사용하려고합니다.
다음과 함께 간단한 요청 사용 curl
:
curl -X POST -H "x-api-user: d904bd62-da08-416b-a816-ba797c9ee265" -H "x-api-key: xxxxxxxxxxx" https://habitica.com/api/v3/user/class/cast/valorousPresence
예상되는 반응과 효과를 얻습니다.
내 Java 코드 사용 :
URI uri = new URIBuilder()
.setScheme("https")
.setHost("habitica.com")
.setPath("/api/v3/user/class/cast/valorousPresence")
.build();
Logger logger = LoggerFactory.getLogger(MyClass.class);
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader(new BasicHeader("x-api-user",getApiUser()));
httpPost.addHeader(new BasicHeader("x-api-key", getApiKey()));
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
logger.info(httpResponse.toString());
return httpResponse.getCode();
Java 호출을 실행할 때 얻는 출력은 다음과 같습니다.
411 Length Required HTTP/1.0
POST 호출을 올바르게 구성하고 있지 않다고 확신합니다. 어떻게해야합니까? Content-Type을 지정하려고 시도했지만 효과가 없습니다. 코드에서 Content-Length를 설정하려고하면 컴파일 오류가 발생합니다 (내가 이해했듯이 이것은 HttpClient5에 의해 백그라운드에서 처리됨). HttpClient5를 사용하는 모든 GET 요청이 제대로 작동합니다.
A에는 POST
항상 페이로드 (콘텐츠)가 있습니다. A POST
내용이없는 것은 드문 일인데 잊은 게 없으신가요?
setEntity()
페이로드가 비어 있더라도 Content-Length
헤더 를 설정하는 엔터티이므로 호출 하여 페이로드를 설정 해야합니다 .
예를 들어 당신이 부를 수 httpPost.setEntity(new StringEntity(""))
있는 세트, Content-Type: text/plain
및 Content-Length: 0
.
Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.
En caso de infracción, por favor [email protected] Eliminar
Déjame decir algunas palabras