1.问题描述
Exception in thread "main" java.lang.IllegalStateException: Invalid use of BasicClientConnectionManager:
//获取请求url状态码为404的url
public class getUrlStatus {
public static void main(String[] args) throws IOException {
httpClientPost();
}
private static void httpClientPost() throws IOException {
//String url = "http://liuxue.xdf.cn/blog/leiting";
String[] urlStr = {
"http://liuxue.xdf.cn/blog/aishanayinuer",
"http://liuxue.xdf.cn/blog/anfei2",
"http://liuxue.xdf.cn/blog/anhong",
"http://liuxue.xdf.cn/blog/anhuijuan",
"http://liuxue.xdf.cn/blog/金碧葳"
};
//创建 高效缓冲输出流
BufferedOutputStream bufOut = new BufferedOutputStream(new FileOutputStream("D:\\404blog.txt"));
for (String url : urlStr) {
//获取连接(注意:每次client.execute(getMethod)之前,都必须new DefaultHttpClient();)否则报错:Exception in thread "main" java.lang.IllegalStateException: Invalid use of Basic...
HttpClient client = new DefaultHttpClient();//导入httpclient-4.5.6.jar
HttpPost post = new HttpPost(url);
try {
ContentProducer cp = new ContentProducer() {
public void writeTo(OutputStream outstream) throws IOException {
Writer writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write("");
writer.flush();
}
};
post.setEntity(new EntityTemplate(cp));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();//HTTP/1.1 404 Not Found
int statusCode = statusLine.getStatusCode();//404
//System.out.println("http状态码:" + statusLine);
if (statusCode==404) {
System.out.println("状态码:" + statusCode);
System.out.println("url :" + url);
//写入文件
bufOut.write(url.getBytes());
bufOut.write("\r\n".getBytes());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("--------------------------------");
}
bufOut.close();
System.out.println("写入成功!");
}
}
(注意:每次client.execute(getMethod)之前,都必须new DefaultHttpClient();因为我是for循环多次请求url,多次获取连接,所以new DefaultHttpClient();要放在for循环内)否则报错:Exception in thread "main" java.lang.IllegalStateException: Invalid use of Basic...