RESTfulClient

RESTfulClient.java

package com.xxx.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
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.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

/**
*
*

 
* 类名标题:RESTful 客户端
* 创建人员:Kang
* 创建时间:2015年3月16日上午9:49:11
* 说明描述:
*

*/
public class RESTfulClient{
public final static String GET=”GET”;
public final static String POST=”POST”;
public final static String PUT=”PUT”;
public final static String DELETE=”DELETE”;

public final static String CHARSET_UTF8="UTF-8";
public final static String CHARSET_GBK="GBK";

public String contentType="JSON";

public final static String CONTENTTYPE_APPLICATION_JSON = "application/json";
public final static String CONTENTTYPE_APPLICATION_JSON_UTF8 = "application/json;charset=UTF-8";
public final static String CONTENTTYPE_TEXT_HTML_UTF8 = "text/html;charset=UTF-8";

public int defaultByteSize=256;

public RESTfulClient(){}

public void setContentType(String contentType){
    this.contentType = contentType;
}

public void setDefaultByteSize(int defaultByteSize){
    this.defaultByteSize = defaultByteSize;
}


/**
 * 
 * <pre>
 * 方法说明:HttpClient Post请求
 * 开发时间:2015年3月16日上午11:05:43
 * 开发人员:Kang
 * @param url   请求URL
 * @param params    请求参数
 * @param requestHeader 请求头
 * @return
 * </pre>
 */
public String post(String url,Map<String,String> params,Map<String,String> requestHeader){
    String responseStr=null;
    HttpClient client = new HttpClient();
    PostMethod postMethod = (PostMethod)getHttpMethod(url,POST,params,requestHeader);
    try{
        responseStr = executeHttpMethod(client,postMethod);
    }catch(HttpException e){
        e.printStackTrace();
    }catch(IOException e){
        e.printStackTrace();
    }
    return responseStr;
}

/**
 * 
 * <pre>
 * 方法说明:HttpClient Post请求
 * 开发时间:2015年3月16日上午11:32:25
 * 开发人员:Kang
 * @param url   请求URL
 * @param params    请求参数
 * @return
 * </pre>
 */
public String post(String url,Map<String,String> params){
    return post(url,params,null);
}

public String post(String url){
    return post(url,null,null);
}

/**
 * 
 * <pre>
 * 方法说明:HttpClient Get请求
 * 开发时间:2015年3月16日上午11:27:00
 * 开发人员:Kang
 * @param url   请求URL
 * @param requestHeader 请求头
 * @return
 * </pre>
 */
public String get(String url,Map<String,String> requestHeader){
    String responseStr=null;
    HttpClient client = new HttpClient();
    GetMethod getMethod = (GetMethod)getHttpMethod(url,GET,null,requestHeader);
    try{
        responseStr = executeHttpMethod(client,getMethod);
    }catch(HttpException e){
        e.printStackTrace();
    }catch(IOException e){
        e.printStackTrace();
    }
    return responseStr;
}


public String get(String url){
    return get(url,null);
}

/**
 * 
 * <pre>
 * 方法说明:获取Method对象[PostMethod,GETMethod...]
 * 开发时间:2015年3月16日上午10:57:45
 * 开发人员:Kang
 * @param url 请求URL
 * @param type  Mehod 类型
 * @param params  请求数据(Post时使用)
 * @param requestHeader 请求头
 * @return Method对象
 * </pre>
 */
public HttpMethod getHttpMethod(String url,String type,Map<String,String> params,Map<String,String> requestHeader){
    HttpMethod method =null;
    if(POST.equals(type)){
        method = new PostMethod(url);
    }else if(GET.equals(type)){
        method = new GetMethod(url);
    }
    if(method instanceof PostMethod && params!=null && params.size()>0){
        method.addRequestHeader("ContentType",CONTENTTYPE_APPLICATION_JSON_UTF8);
        if("JSON".equalsIgnoreCase(contentType)){
            try{
                RequestEntity re = new StringRequestEntity(JSONObject.fromObject(params).toString(),CONTENTTYPE_APPLICATION_JSON,CHARSET_UTF8);
                ((PostMethod)method).setRequestEntity(re);
            }catch(UnsupportedEncodingException e){
                e.printStackTrace();
            }
        }else{
            Set<String> keySet = params.keySet();
            Iterator<String> keyIt = keySet.iterator();
            while(keyIt.hasNext()){
                String key = keyIt.next();
                ((PostMethod)method).addParameter(key,String.valueOf(params.get(key)));
            }
        }
    }
    if(requestHeader!=null && requestHeader.size()>0){
        Set<String> keySet = requestHeader.keySet();
        Iterator<String> keyIt = keySet.iterator();
        while(keyIt.hasNext()){
            String key = keyIt.next();
            method.addRequestHeader(key,String.valueOf(requestHeader.get(key)));
        }
    }
    return method;
}

/**
 * 
 * <pre>
 * 方法说明:执行Method请求
 * 开发时间:2015年3月16日上午11:04:50
 * 开发人员:Kang
 * @param client  HttpClient对象
 * @param method  Method
 * @return  返回结果
 * @throws HttpException
 * @throws IOException
 * </pre>
 */
public String executeHttpMethod(HttpClient client,HttpMethod method) throws HttpException, IOException{
    int responseCode = client.executeMethod(method);
    if(HttpStatus.SC_OK != responseCode)
        throw new HttpException("HTTP "+method.getName()+" Request Failed with Error code : "
              + responseCode + new String(method.getResponseBody(),CHARSET_UTF8));
    /*
    InputStream is =  method.getResponseBodyAsStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] b= new byte[defaultByteSize];
    int c=-1;
    while((c=is.read(b))!=-1){
        out.write(b,0,c);
    }
    out.close();
    */
    return new String(method.getResponseBody(),CHARSET_UTF8);
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值