一个Httpclient工具函数的案例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_18895975/article/details/76084577

注意事项

实际测试中需要2个核心jar
httpclient-4.5.jar
httpcore-4.4.1.jar
版本尽量高,否则会出现低版本莫名的错误

使用的jar目录

httpclient-4.5.jar
httpcore-4.4.1.jar
以下的包是为了处理响应得到的Json
commons-beanutils-1.8.3.jar
commons-collections-3.2.1.jar
commons-lang-2.4.jar
commons-logging-1.1.1.jar
ezmorph-1.0.6.jar
json-lib-2.2.3.jar

案例代码

package com;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
/**
 * @author wangjun
 * @Description 远程接口案例
 * 该工程同时集成了对JSONObject和JSONArray的支持
 */
@SuppressWarnings("deprecation")
public class TeleService{
    /**
     * 主函数
     * */
    public static void main(String[] args) {
        String myPara="王";
        if(null!=args && args.length>0){ myPara=args[0];}
        String baseUrl = "http://www.baidu.com/s?";
        Map<String,String> map=new HashMap<String,String>();
        map.put("wd", myPara);
        map.put("ie", "UTF-8");
        System.out.println(TeleRequestMethod(baseUrl, map, "UTF-8", "UTF-8", "GET"));
    }
    /** HttpClient远程请求基本方法
     * @param baseUrl 基础地址 http://www.baidu.com
     * @param parm 其他参数组
     * @param CharsetRequest   使用何种字符集编码请求参数               默认"UTF-8" "GBK" "ISO-8859-1"
     * @param CharsetRequest   使用何种字符集解析响应得到字节流     默认"UTF-8" "GBK" "ISO-8859-1"
     * @param RequestMethod "POST"和"GET"2种
     * */
    public static String TeleRequestMethod(String baseUrl,Map<String,String> parm,String CharsetRequest,String CharsetResponse,String RequestMethod) {
//      HttpParams httpParameters = new BasicHttpParams();  
//      HttpConnectionParams.setConnectionTimeout(httpParameters, 10*1000);//设置请求超时10秒  
//      HttpConnectionParams.setSoTimeout(httpParameters, 10*1000);        //设置等待数据超时10秒  
//      HttpConnectionParams.setSocketBufferSize(httpParameters, 8192);    //套接字大小
//      HttpClient httpclient = new DefaultHttpClient(httpParameters);     //此时构造DefaultHttpClient时将参数传入  
        HttpClient httpclient = new DefaultHttpClient();//主要对象
        String strResult = "";//响应结果
        StringBuffer sbf = new StringBuffer();//结果集合
        HttpResponse response = null;
        try {
            //额外参数赋值
            List<NameValuePair>  nameValuePairs= new ArrayList<NameValuePair>();
            if(null!=parm){for (String in : parm.keySet()) {
                nameValuePairs.add(new BasicNameValuePair(in, parm.get(in)));//(name 张三)
            }}
            //GET或POST
            if(!ISNull(RequestMethod)){
                if("GET".equals(RequestMethod.toUpperCase())){
                    String baseUrlNew = baseUrl;
                    if(nameValuePairs.size()>0){baseUrlNew = baseUrl + URLEncodedUtils.format(nameValuePairs, CharsetRequest);}//按照字符集对请求参数进行编码,暂时固定 
                    HttpGet httpget   = new HttpGet(baseUrlNew);
                    httpget.addHeader("Content-type","application/x-www-form-urlencoded");
                    response = httpclient.execute(httpget);
                }else if("POST".equals(RequestMethod.toUpperCase())) {
                    HttpPost httppost = new HttpPost(baseUrl);
                    httppost.addHeader("Content-type","application/x-www-form-urlencoded");
                    if(nameValuePairs.size()>0){httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,   CharsetRequest));}//按照字符集对请求参数进行编码,暂时固定
                    response = httpclient.execute(httppost);
                }
            }
            //结果流封装为字符串
            if (response.getStatusLine().getStatusCode() == 200) {//状态200是成功
                InputStream ins = response.getEntity().getContent();//读返回数据 
                BufferedReader br = new BufferedReader(new InputStreamReader(ins, CharsetResponse));// 按指定的字符集解析响应字符串
                String line = null;
                while ((line = br.readLine()) != null) { sbf.append(line); }
                br.close();
            } else {
                String err = response.getStatusLine().getStatusCode() + "";
                strResult += "发送失败:" + err;
                System.out.println(strResult);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sbf.toString();
    }
    public static boolean ISNull(String para) {
        if("".equals(para) || null== para){
            return true;
        }return false;
    }
}

结果展示

<!DOCTYPE html><!--STATUS OK--> <html>  <head>              <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">      <meta http-equiv="content-type" content="text/html;charset=utf-8">      <meta content="always" name="referrer">        <meta name="theme-color" content="#2932e1">        <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />        <link rel="icon" sizes="any" mask href="//www.baidu.com/img/baidu.svg">        <link rel="search" type="application/opensearchdescription+xml" href="/content-search.xml" title="百度搜索" />                 <title>王_百度搜索</title>               ...等等

猜你喜欢

转载自blog.csdn.net/qq_18895975/article/details/76084577