HttpClient (POST GET PUT)请求

package com.curender.web.server.http;

import java.io.IOException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.curender.dal.util.ConstantsDal;

/**
 * HttpClient GET POST PUT 请求
 * @author huang
 * @date 2013-4-10
 */
public class HttpRequest
{

    protected static Log log = LogFactory.getLog(HttpRequest.class);
    private static HttpRequest httpRequst=null;   
    private HttpRequest(){}  
    public static HttpRequest getInstance(){
        if(httpRequst==null){
            synchronized(HttpRequest.class){
                if(httpRequst == null){
                    httpRequst=new HttpRequest();
                }
            }  
        }
        return httpRequst;
    }
    
    /**
     * HttpClient GET请求
     * @author huang
     * @date 2013-4-9
     * @param uri
     * @return resStr 请求返回的JSON数据
     */
    public String doGet(String uri){
        String resStr = null;
        HttpClient htpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(ConstantsDal.SERVER_URL+uri);
        getMethod.getParams().setParameter( HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());     
        try{
            int statusCode = htpClient.executeMethod( getMethod );
//            log.info(statusCode);
            if(statusCode != HttpStatus.SC_OK){              
                log.error("Method failed: "+getMethod.getStatusLine());
                return resStr;
            }           
            byte[] responseBody = getMethod.getResponseBody();         
            resStr = new String(responseBody,HttpConstants.ENCODED);
        } catch (HttpException e) {
            log.error("Please check your provided http address!");  //发生致命的异常,可能是协议不对或者返回的内容有问题
        } catch (IOException e) {
            log.error( "Network anomaly" );  //发生网络异常
        }finally{
            getMethod.releaseConnection(); //释放连接
        }
        return resStr;
    }
    
    /**
     * HttpClient POST请求
     * @author huang
     * @date 2013-4-9
     * @param s_user
     * @return resStr 请求返回的JSON数据
     */
    @SuppressWarnings( "deprecation" )
    public String doPost(String uri,String jsonObj){    
        String resStr = null;
        HttpClient htpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(ConstantsDal.SERVER_URL+uri);
        postMethod.addRequestHeader( "Content-Type","application/json" );  
        postMethod.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, HttpConstants.ENCODED );
        postMethod.setRequestBody( jsonObj );
        try{
            int statusCode = htpClient.executeMethod( postMethod );
//            log.info(statusCode);
            if(statusCode != HttpStatus.SC_OK){
              //post和put不能自动处理转发          301:永久重定向,告诉客户端以后应从新地址访问    302:Moved Temporarily  
                if(statusCode == HttpStatus.SC_MOVED_PERMANENTLY||statusCode == HttpStatus.SC_MOVED_TEMPORARILY){
                    Header locationHeader = postMethod.getResponseHeader( "location" );
                    String location = null;
                    if(locationHeader!=null){
                        location = locationHeader.getValue();
                        log.info("The page was redirected to :"+location);
                    }else{
                        log.info("Location field value is null");
                    }
                }else{
                    log.error("Method failed: "+postMethod.getStatusLine());                    
                }
                return resStr;
            }                     
            byte[] responseBody = postMethod.getResponseBody();           
            resStr = new String(responseBody,HttpConstants.ENCODED);  
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            postMethod.releaseConnection();
        }
        return resStr;
    }
    
    /**
     * HttpClient PUT请求
     * @author huang
     * @date 2013-4-10
     * @return
     */
    @SuppressWarnings( "deprecation" )
    public String doPut(String uri,String jsonObj){
        String resStr = null;
        HttpClient htpClient = new HttpClient();
        PutMethod putMethod = new PutMethod(ConstantsDal.SERVER_URL+uri);
        putMethod.addRequestHeader( "Content-Type","application/json" );
        putMethod.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, HttpConstants.ENCODED );
        putMethod.setRequestBody( jsonObj );
        try{
            int statusCode = htpClient.executeMethod( putMethod );
//            log.info(statusCode);
            if(statusCode != HttpStatus.SC_OK){
                log.error("Method failed: "+putMethod.getStatusLine());
                return null;
            }  
            byte[] responseBody = putMethod.getResponseBody();         
            resStr = new String(responseBody,HttpConstants.ENCODED);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            putMethod.releaseConnection();
        }
        return resStr;
    }
}

 HttpConstants.ENCODED=“UTF-8”

ConstantsDal.SERVER_URL=http://ip/

HttpClient是一个开源的HTTP客户端库,用于发送HTTP请求和接收HTTP响应。它提供了丰富的功能,包括GET、POST、PUT、DELETE等请求方法的支持,以及请求头、请求体、响应头、响应体的处理。 对于HttpClientPOST请求,可以按照以下步骤进行操作: 1. 创建HttpClient对象: HttpClient httpClient = HttpClientBuilder.create().build(); 2. 创建HttpPost对象,并设置请求URL: HttpPost httpPost = new HttpPost("http://example.com/api"); 3. 设置请求参数: 通过NameValuePair或者HttpEntity来设置请求参数,例如: List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("param1", "value1")); params.add(new BasicNameValuePair("param2", "value2")); httpPost.setEntity(new UrlEncodedFormEntity(params)); 4. 设置请求头: 可以通过httpPost.setHeader()方法设置请求头,例如: httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); 5. 执行请求并获取响应: 使用HttpClient对象执行HttpPost请求,并获取HttpResponse对象,例如: HttpResponse response = httpClient.execute(httpPost); 6. 处理响应结果: 可以通过HttpResponse对象获取响应状态码、响应头和响应体等信息,例如: int statusCode = response.getStatusLine().getStatusCode(); Header[] headers = response.getAllHeaders(); String responseBody = EntityUtils.toString(response.getEntity()); 以上就是使用HttpClient进行POST请求的基本步骤。当然,在实际使用中还可以根据需要设置其他参数,如超时时间、代理等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值