我在java中有一个要求,我需要创建一个HTTP请求服务来将内容发布到其他服务。使用服务使用来自HTTP请求的数据。 我面临的问题是,有时消费服务会出现一些错误,并且不会将任何响应返回给HTTP服务。
HTTP请求服务捕获响应的状态代码以了解请求已通过。当我没有得到回复时,有没有办法知道HTTP请求通过。我需要验证我的4xx(例如404)状态代码的HTTP请求。这是用于执行HTTP POST的JAVA函数
public boolean postStringXMLContentToUrl(String content,
String mimetype, String charset, String url) {
boolean isContentPosted = true;
BufferedReader br = null;
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
HttpResponse httpResponse;
try {
ContentType contentType = ContentType.create(mimetype, charset);
StringEntity StringContentEntity = new StringEntity(
content, contentType);
post.setEntity(StringContentEntity);
httpResponse = client.execute(post);
int returnCode = httpResponse.getStatusLine().getStatusCode();
log.info("Status Code = "+returnCode);
if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
log.warn("The Post method is not implemented by this URI");
isContentPosted = false;
}
else if(returnCode == HttpStatus.SC_NOT_FOUND)
{
log.warn("Service not found ");
isContentPosted = false;
}
else {
if(new String(new Integer(returnCode).toString()).matches("2[0-9][0-9]")) //Status code 2xx for e.g. 200, 201 etc
{
isContentPosted = true;
log.info("HTTP POST request sent successfully to"+url+" with content \n" + content);
}
else
{
isContentPosted = false;
log.info("HTTP POST request unsuccessfull to"+url);
}
br = new BufferedReader(new InputStreamReader(
httpResponse.getEntity().getContent()));
String readLine;
log.info("Response from HTTP POST to " + url);
while (((readLine = br.readLine()) != null)) {
log.info(readLine);
}
}
} catch (Exception e) {
isContentPosted = false;
log.error("Error While sending HTTP POST request to "+url);
log.error(e.getMessage());
} finally {
post.releaseConnection();
if (br != null)
try {
br.close();
} catch (Exception fe) {
isContentPosted = false;
log.error("Error While sending HTTP POST request to "+url);
log.error(fe.getMessage());
}
}
return isContentPosted;
}