Java HttpHelper类,可携带Cookie,使用HttpClient4
1 public String GetHtml(String URL) 2 { 3 DefaultHttpClient httpClient = new DefaultHttpClient(); 4 HttpGet request=new HttpGet(URL); 5 request.addHeader("Accept", "application/javascript, */*;q=0.8"); 6 request.addHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)"); 7 request.addHeader("Referer", Referer); 8 if (cookie!=null){ 9 httpClient.setCookieStore(cookie); 10 } 11 try { 12 13 HttpResponse httpResponse=httpClient.execute(request); 14 String res=EntityUtils.toString(httpResponse.getEntity()); 15 cookie=httpClient.getCookieStore(); 16 httpClient.getConnectionManager().shutdown(); 17 return(res); 18 } catch (IOException e) { 19 return(e.toString()); 20 } catch (ParseException e){ 21 return(e.toString()); 22 } 23 } 24 25 public String GetHtml(String URL,String PostData) 26 { 27 DefaultHttpClient httpClient=new DefaultHttpClient(); 28 HttpPost request=new HttpPost(URL); 29 if (cookie!=null){ 30 httpClient.setCookieStore(cookie); 31 } 32 try { 33 StringEntity reqEntity = new StringEntity(PostData); 34 reqEntity.setContentType("application/x-www-form-urlencoded"); 35 36 request.addHeader("Accept", "application/javascript, */*;q=0.8"); 37 request.addHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)"); 38 request.addHeader("Referer",Referer); 39 request.setEntity(reqEntity); 40 HttpResponse httpResponse=httpClient.execute(request); 41 String res=EntityUtils.toString(httpResponse.getEntity()); 42 cookie=httpClient.getCookieStore(); 43 httpClient.getConnectionManager().shutdown(); 44 return(res); 45 } catch (IOException e) { 46 return(e.toString()); 47 } catch (ParseException e){ 48 return(e.toString()); 49 } 50 } 51 }