HttpClient发送请求

本文介绍了一种使用Java模拟HTTP GET和POST请求的方法,包括如何构造请求、处理响应及管理cookies等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可以模拟浏览器的get请求和post请求,需要的包请搜索下载commons-httpclient.jar

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

import com.xdatasystem.contactsimporter.UpdateableCookieStore;

public class HTTPUtil {
 /**
  * 简单的get 请求
  * @param url
  * @return
  */
 public static String httpSimpleGet(String url){
  String result = null;
  DefaultHttpClient client =new DefaultHttpClient();
  HttpGet get=new HttpGet(url);
  HttpParams params=client.getParams();
  HttpConnectionParams.setConnectionTimeout(params, 10000);//设置请求超时时间为10秒
  
  HttpResponse response=null;
  try{
   response=client.execute(get);
   HttpEntity entity=response.getEntity();//得到http的内容
   result=EntityUtils.toString(entity);

  }catch(Exception e){
   System.out.println(e.getMessage());
  }finally{
   if(client!=null){
    client.getConnectionManager().shutdown();
   }
  }
  return result;
 }
 //带参数的get请求
 public static String httpGet(String url,Map params){
  
  if(params!=null){
   StringBuffer buffer=new StringBuffer(url);
   buffer.append("?");
   Set<String> keys=params.keySet();
   Iterator it=keys.iterator();
   while(it.hasNext()){
    String key=(String) it.next();
    buffer.append(key);
    buffer.append("=");
    buffer.append(params.get(key));
    buffer.append("&");   }
   url=buffer.toString();
  }
  System.out.println(url);
  String result = null;
  DefaultHttpClient client =new DefaultHttpClient();
  HttpGet get=new HttpGet(url);
  HttpParams clientParams=client.getParams();
  HttpConnectionParams.setConnectionTimeout(clientParams, 10000);//设置请求超时时间为10秒
  
  HttpResponse response=null;
  try{
   response=client.execute(get);
   HttpEntity entity=response.getEntity();//得到http的内容
   result=EntityUtils.toString(entity);

  }catch(Exception e){
   System.out.println(e.getMessage());
  }finally{
   if(client!=null){
    client.getConnectionManager().shutdown();
   }
  }
  return result;
  
 }
 /**
  * post请求
  */
 public static String httpPost(String reqUrl,Map reqParams) throws ClientProtocolException, IOException{
  String result=null;
  DefaultHttpClient client;
     client = new DefaultHttpClient();
     client.setCookieStore(new UpdateableCookieStore());
     //以下注释的内容是添加初始的cookie信息
//     BasicClientCookie clientCookie = new BasicClientCookie("", "0.01" + System.currentTimeMillis());
//     clientCookie.setDomain(".126.com");
//     clientCookie.setPath("/");
//     client.getCookieStore().addCookie(clientCookie);
     //构建参数集合,
     ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
     //请求必须的参数
     if(reqParams!=null){
   Set<String> keys=reqParams.keySet();
   Iterator it=keys.iterator();
   while(it.hasNext()){
    String key=(String) it.next();
    params.add(new BasicNameValuePair(key, (String) reqParams.get(key)));
   }
  }

     //构建http头
     List headers = new ArrayList();
     headers.add(new BasicHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; CIBA; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"));
     client.getParams().setParameter("http.default-headers", headers);
     HttpPost post = new HttpPost(reqUrl);
     post.addHeader("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*");
     post.addHeader("Accept-Language", "zh-cn");
     post.addHeader("Content-Type", "application/x-www-form-urlencoded");
     post.addHeader("Accept-Encoding", "ISO-8859-1,utf-8;gbk;default");
     post.addHeader("Host", reqUrl);
     post.addHeader("Cache-Control", "no-cache");
     post.addHeader("Connection", "Keep-Alive");
     post.addHeader("UA-CPU", "x64");

     post.addHeader("Referer", reqUrl);//链接到reqUrl时所在的页面,某些网站可以不做设置

     post.setEntity(new UrlEncodedFormEntity(params, "gbk"));

     HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
     HttpProtocolParams.setUseExpectContinue(post.getParams(), false);
     //发送post请求
     HttpResponse resp = client.execute(post);
     InputStream content = null;

  try {
   //得到输入流
   content = resp.getEntity().getContent();

   try {
    // 获取返回信息
    BufferedReader in = new BufferedReader(new InputStreamReader(
      content, "GB2312"));
    StringBuffer buffer = new StringBuffer();
    String line;
    while ((line = in.readLine()) != null) {
     buffer.append(line).append("\n");
    }
    // 输出获取的信息
    result = buffer.toString();
    System.out.println(result);
    // 获取cookie
    List<Cookie> cs = client.getCookieStore().getCookies();
    for (Cookie cookie : cs) {
     System.out.println("name:" + cookie.getName() + ",value="
       + cookie.getValue());
    }
   } finally {
    if (content != null) {
     content.close();
    }
   }
   return result;
  } catch (Exception e) {
   e.printStackTrace();
   return result;
  }
 }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值