Problem sending HTTP post request in Java
Hey, I'm trying to post an http request with xml body. This is my code:
public void setBla(String url, String cookie, SomeEnum status) {
String availabilityUrl = url;
HttpPost httpPost = new HttpPost(availabilityUrl + VERSION_TEXT);
httpPost.setHeader(HttpHeaders.AUTHORIZATION, LP_AUTH_HEADER_VALUE);
httpPost.setHeader(HttpHeaders.ACCEP开发者_JS百科T, MediaType.APPLICATION_XML);
httpPost.setHeader("X-HTTP-Method-Override", HttpMethod.PUT);
httpPost.setHeader("Cookie", cookie);
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML);
HttpResponse response = null;
try {
HttpEntity entity = new StringEntity("<availability><chat>" + status + "</chat></availability>", HTTP.UTF_8);
httpPost.setEntity(entity);
response = m_httpClient.execute(httpPost);
}
catch (Exception e) {
e.printStackTrace();
}
}
Im getting a bad request from the AppServer (400), and in debug I can see that HttpEntity also has ContentType header and its set to text/plain... Why? What am I doing wrong? What is the right way to send a request with a body?
SOLUTION:
OK.. I got it.. Thanks skaffman, that was pretty close :) AbstractHttpEntity declare setContentType function...
Sorry for the bother..
Udi
Assuming this is HttpClient 4.1, then you're not using the appropriate constructor for StringEntity
, you probably need to specify the mime type as well as the charset, e.g.
HttpEntity entity = new StringEntity(xmlString, "application/xml", HTTP.UTF_8);
See javadoc.
精彩评论