`
roddy
  • 浏览: 16878 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

HttpClient Call Website

    博客分类:
  • Java
 
阅读更多
Need Jar:
htmlunit-2.17-OSGi.jar

 @SuppressWarnings({ "finally", "deprecation" })
	public static String executeGet(String url,String host,String cookie) throws IOException {
		BufferedReader in = null;

		String content = null;
		int responseCode = 0;
		DefaultHttpClient client = new DefaultHttpClient();
		try {
			HttpGet request = new HttpGet();
			request.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			request.addHeader("Accept-Language","zh-TW,zh;q=0.8,en-US;q=0.6,en;q=0.4");
			request.addHeader("Connection","keep-alive");
			request.addHeader("Cookie",cookie);
			request.addHeader("Host",host);
			request.addHeader("Upgrade-Insecure-Requests","1");
			request.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
			
			request.setURI(new URI(url));
			HttpResponse response = client.execute(request);
			responseCode = response.getStatusLine().getStatusCode();
			//System.out.println("Url: "+url+" Response = "+response.getStatusLine().getStatusCode());
			int count=1;
			while(responseCode!=200 && count<=3){
				count ++;
				System.out.println("--------call again......");
				Thread.sleep(3000);
				client.close();
				client = new DefaultHttpClient();
				response = client.execute(request);
				responseCode = response.getStatusLine().getStatusCode();
			}

			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			
			content = sb.toString();
		}catch(Exception e){
			e.printStackTrace();
		} finally {
			if(in!=null)
				in.close();
			if(client!=null)
			client.close();
			return content;
		}
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics