java返回状态码代码 java返回状态码代码怎么写

java获取url状态码问题httpclient默认自动处理redirect , 返回200是因为它已经自动跳转了 , 如果想抓到301状态,可以手动修改跳转规则(以下代码基于httpclient 4.5):
public static void main(String[] args) {
CloseableHttpClient
httpclient = HttpClients.custom().setRedirectStrategy(new
DefaultRedirectStrategy() {
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context){
return false;
}}).build();
HttpClientContext context = HttpClientContext.create();
HttpGet httpget = new HttpGet("
);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpget, context);
HttpHost target = context.getTargetHost();
ListURI redirectLocations = context.getRedirectLocations();
URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations);
System.out.println("Final HTTP location: "location.toASCIIString());
System.out.println(response.getStatusLine());
// Expected to be an absolute URI
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
java如何返回各种状态码对你所询问的Java如何返回各种状态码,其实这是一个系统调配命令设置,需要借用不同的返回命令实现代码的转换操作
怎样用java获取URL返回状态码可以用以下代码参考一下,如何获取URL返回状态码:
//用getResponseCode可以获取URL返回状态码
String surl = "";
try {
surl="你的url";
URL url = new URL(surl);
URLConnection rulConnection= url.openConnection();
HttpURLConnection httpUrlConnection=(HttpURLConnection) rulConnection;
httpUrlConnection.setConnectTimeout(300000);
httpUrlConnection.setReadTimeout(300000);
httpUrlConnection.connect();
String code = new Integer(httpUrlConnection.getResponseCode()).toString();
String message = httpUrlConnection.getResponseMessage();
System.out.println("getResponseCode code ="code);
System.out.println("getResponseMessage message ="message);
if(!code.startsWith("2")){
throw new Exception("ResponseCode is not begin with 2,code=" code);
}
System.out.println(getCurDateTime() "连接" surl "正常");
}catch(Exception ex){
System.out.println(ex.getMessage());
}
【java返回状态码代码 java返回状态码代码怎么写】关于java返回状态码代码和java返回状态码代码怎么写的介绍到此就结束了 , 不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。

    推荐阅读