当前位置: 首页 > 工具软件 > httphelper > 使用案例 >

Java HttpHelper类,可携带Cookie,使用HttpClient4

古文康
2023-12-01
public String GetHtml(String URL)
 {
  DefaultHttpClient httpClient = new DefaultHttpClient();
  HttpGet request=new HttpGet(URL); 
  request.addHeader("Accept", "application/javascript, */*;q=0.8");
  request.addHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)");
  request.addHeader("Referer", Referer);
  if (cookie!=null){
   httpClient.setCookieStore(cookie);
  } 
  try {
   
   HttpResponse httpResponse=httpClient.execute(request); 
   String res=EntityUtils.toString(httpResponse.getEntity());
   cookie=httpClient.getCookieStore();
   httpClient.getConnectionManager().shutdown();
   return(res);
  } catch (IOException  e) {
   return(e.toString());
  } catch (ParseException e){
   return(e.toString());
     } 
 }
 
 public String GetHtml(String URL,String PostData)
 {
  DefaultHttpClient httpClient=new DefaultHttpClient();
  HttpPost request=new HttpPost(URL); 
  if (cookie!=null){
   httpClient.setCookieStore(cookie);
  } 
  try {
   StringEntity reqEntity = new StringEntity(PostData);
   reqEntity.setContentType("application/x-www-form-urlencoded");
   
   request.addHeader("Accept", "application/javascript, */*;q=0.8");
   request.addHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)");
   request.addHeader("Referer",Referer);
   request.setEntity(reqEntity);
   HttpResponse httpResponse=httpClient.execute(request);
   String res=EntityUtils.toString(httpResponse.getEntity());
   cookie=httpClient.getCookieStore();
   httpClient.getConnectionManager().shutdown();
   return(res);
  } catch (IOException  e) {
   return(e.toString());
  } catch (ParseException e){
   return(e.toString());
     } 
 }
 }
 类似资料: