java模拟http get和post 提交 httpclient

原文地址:http://blog.csdn.net/miniyaner/article/details/12423435

原文post的处理不是很方便,本人对其进行了改造,下面为改造完后的代码:

接收参数可以直接使用:request.getParameter("xxx")

使用httpclient工具包commons-httpclient-3.1.jar,依赖commons-logging-1.0.4.jar和commons-codec-1.3.jar。

package util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.util.URIUtil;

/**  
 *   
 *   
 * <p>Title:HttpTookitEnhance</p>  
 * <p>Description: httpclient模拟http请求,解决返回内容乱码问题</p>  
 * <p>Copyright: Copyright (c) 2010</p>  
 * <p>Company: </p>  
 * @author libin  
 * @version 1.0.0  
 */  
public class HttpTookitEnhance   
{   
	
      /**   
       * 执行一个HTTP GET请求,返回请求响应的HTML   
       *   
       * @param url                 请求的URL地址   
       * @param queryString 请求的查询参数,可以为null   
       * @param charset         字符集   
       * @param pretty            是否美化   
       * @return 返回请求响应的HTML   
       */  
      public static String doGet ( String url, String queryString, String charset, boolean pretty )   
      {   
            StringBuffer response = new StringBuffer();   
            HttpClient client = new HttpClient();   
            HttpMethod method = new GetMethod(url);   
            try  
            {   
                  if ( queryString != null && !queryString.equals("") )   
                        //对get请求参数做了http请求默认编码,好像没有任何问题,汉字编码后,就成为%式样的字符串    
                        method.setQueryString(URIUtil.encodeQuery(queryString));   
                  client.executeMethod(method);   
                  if ( method.getStatusCode() == HttpStatus.SC_OK )   
                  {   
                        BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));   
                        String line;   
                        while ( ( line = reader.readLine() ) != null )   
                        {   
                              if ( pretty )   
                                    response.append(line).append(System.getProperty("line.separator"));   
                              else  
                                    response.append(line);   
                        }   
                        reader.close();   
                  }   
            }   
            catch ( URIException e )   
            {   
            	e.printStackTrace();
            }   
            catch ( IOException e )   
            {   
            	e.printStackTrace();
            }   
            catch ( Exception e )   
            {   
            	e.printStackTrace();
            } 
            finally  
            {   
                  method.releaseConnection();   
            }   
            return response.toString();   
      }   
  
      /**   
       * 执行一个HTTP POST请求,返回请求响应的HTML   
       *   
       * @param url         请求的URL地址   
       * @param params    请求的查询参数,可以为null   
       * @param charset 字符集   
       * @param pretty    是否美化   
       * @return 返回请求响应的HTML   
       */  
      public static String doPost ( String url, Map<String, String> params, String charset, boolean pretty )   
      {   
            StringBuffer response = new StringBuffer();   
            HttpClient client = new HttpClient();   
            PostMethod method = new PostMethod(url);
            method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset="+charset);
            //设置Http Post数据    
            if ( params != null )   
              {   
            	 	NameValuePair[] data = new NameValuePair[params.size()];
            	 	int i = 0;
                    for ( Map.Entry<String, String> entry : params.entrySet() )   
                    {   
                    	NameValuePair p = new NameValuePair(entry.getKey(), entry.getValue());   
                        data[i]=p;
                        i++;
                    }   
                    method.setRequestBody(data); 
              }   
            try  
            {   
                  client.executeMethod(method);   
                  if ( method.getStatusCode() == HttpStatus.SC_OK )   
                  {   
                        BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));   
                        String line;   
                        while ( ( line = reader.readLine() ) != null )   
                        {   
                              if ( pretty )   
                                    response.append(line).append(System.getProperty("line.separator"));   
                              else  
                                    response.append(line);   
                        }   
                        reader.close();   
                  }   
            }
            catch ( URIException e )   
            {   
            	e.printStackTrace();
            }   
            catch ( IOException e )   
            {   
            	e.printStackTrace();
            }
            catch ( Exception e )   
            {   
            	e.printStackTrace();
            }   
            finally  
            {   
                  method.releaseConnection();   
            }   
            return response.toString();   
      }   
  
      public static void main ( String [] args )   
      {   
    	  
    	  Map<String, String> params = new HashMap<String,String>();
  	  	  params.put("password", "123123");
  	  	  params.put("nickname", "洋洋");
          String y = doPost("http://127.0.0.1:8080/", params, "UTF-8", true);   
          System.out.println(y);
      }   
  
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpClient 是一个开源的 HTTP 客户端库,用于发送 HTTP 请求和接收响应。它提供了一系列的方法来发送 GET 和 POST 请求,并设置请求头。 以下是使用 HttpClient 发送 GET 请求的示例代码: ```java import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; public class HttpClientExample { public static void main(String[] args) { HttpClient httpClient = HttpClientBuilder.create().build(); try { URI uri = new URI("http://example.com/api"); HttpGet getRequest = new HttpGet(uri); // 设置请求头 getRequest.addHeader("User-Agent", "Mozilla/5.0"); HttpResponse response = httpClient.execute(getRequest); // 处理响应 System.out.println(response.getStatusLine().getStatusCode()); // 其他处理逻辑... } catch (URISyntaxException | IOException e) { e.printStackTrace(); } } } ``` 以上示例中,我们创建了一个 HttpClient 对象,并使用 `HttpGet` 请求发送 GET 请求。然后,我们通过 `addHeader` 方法设置了请求头中的 User-Agent 字段,模拟了一个浏览器的 User-Agent。最后,使用 `httpClient.execute(getRequest)` 方法发送请求并获取响应。 以下是使用 HttpClient 发送 POST 请求的示例代码: ```java import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) { HttpClient httpClient = HttpClientBuilder.create().build(); try { URI uri = new URI("http://example.com/api"); HttpPost postRequest = new HttpPost(uri); // 设置请求头 postRequest.addHeader("Content-Type", "application/json"); // 设置请求体 StringEntity requestBody = new StringEntity("{\"key\":\"value\"}"); postRequest.setEntity(requestBody); HttpResponse response = httpClient.execute(postRequest); // 处理响应 System.out.println(response.getStatusLine().getStatusCode()); HttpEntity responseEntity = response.getEntity(); String responseString = EntityUtils.toString(responseEntity); System.out.println(responseString); // 其他处理逻辑... } catch (URISyntaxException | IOException e) { e.printStackTrace(); } } } ``` 以上示例中,我们使用 `HttpPost` 请求发送 POST 请求。同样,我们通过 `addHeader` 方法设置了请求头中的 Content-Type 字段为 application/json。然后,我们设置了请求体为一个 JSON 字符串。最后,使用 `httpClient.execute(postRequest)` 方法发送请求并获取响应。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值