利用HTTPClient模块中HttpGet和HttpPost 发送接口请求

           HttpClient常用HttpGet和HttpPost这两个类,分别对应Get方式和Post方式。

           无论是使用HttpGet,还是使用HttpPost,都必须通过如下3步来访问HTTP资源。

           1.创建HttpGetHttpPost对象,将要请求的URL通过构造方法传入HttpGetHttpPost对象。

           2.使用DefaultHttpClient类的execute方法发送HTTP GETHTTP POST请求,并返回HttpResponse对象。

           3.通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。

           如果使用HttpPost方法提交HTTP POST请求,则需要使用HttpPost类的setEntity方法设置请求参数。参数则必须用NameValuePair[]数组存储。

     以发送连接请求时,需要设置链接超时和请求超时等参数,否则会长期停止或者崩溃。

  1. HttpParams httpParameters = new BasicHttpParams();  
  2. HttpConnectionParams.setConnectionTimeout(httpParameters, 10*1000);//设置请求超时10秒  
  3. HttpConnectionParams.setSoTimeout(httpParameters, 10*1000); //设置等待数据超时10秒  
  4. HttpConnectionParams.setSocketBufferSize(params, 8192);  
  5. HttpClient httpclient = new DefaultHttpClient(httpParameters); //此时构造DefaultHttpClient时将参数传入


/** Http请求集成类
 *  HttpPost
 */
public class HttpServiceClient {
    private static String serviceUrl;

    /**
     * Webservice 统一访问接口
     * @param apiName 接口名称
     * @param paramName 参数名称
     * @param paramValue 参数数值
     */

    public static String doAction(String apiName, List<String> paramName, List<String> paramValue){
        String result = null;
        try{
            HttpClient client=new DefaultHttpClient();

//      HttpGet httpRequst = new HttpGet(URI uri);  
//      HttpGet httpRequst = new HttpGet(String uri);  
//      创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。 

            HttpPost httpPostReq=new HttpPost(serviceUrl+apiName);
//            httpPostReq.setHeader("Content-Type", "application/Json");
//            JSONObject param = new JSONObject();

//            POST 将需要传送的参数与值转化为相HttpPost能接受的类(key/value) Post不支持复杂数据类型,因为post没有定义传输数据结构的语义和规则
            ArrayList<NameValuePair> paramList=new ArrayList<NameValuePair>();
            for (int i = 0; i < paramName.size(); i++){
                String name = paramName.get(i);
                NameValuePair param = new BasicNameValuePair(name, paramValue.get(i));
                paramList.add(param);
            }
//            StringEntity se = new StringEntity(param.toString());
//            se.setContentEncoding(HTTP.UTF_8);
//            先将参数放入List,填入POST Entity中 ,再对参数进行URL编码

            httpPostReq.setEntity(new UrlEncodedFormEntity(paramList, HTTP.UTF_8));
//            使用DefaultHttpClient类的execute方法发送HTTP GET请求,并返回HttpResponse对象。
            HttpResponse resp = client.execute(httpPostReq);
            if(resp.getStatusLine().getStatusCode()== HttpStatus.SC_OK){ //请求成功后执行
                BufferedReader reader=new BufferedReader(
                        new InputStreamReader(resp.getEntity().getContent())
                );
                StringBuffer buff=new StringBuffer();
                String inputLine;
                while((inputLine=reader.readLine()) != null){
                    buff.append(inputLine);
                }  //result为调用接口后所返回的值
                result = buff.toString();
                Log.i(apiName, result);    //获取响应对就的参数
            }

        }catch(Exception e){
            Log.i("HttpServiceClient", e.toString());
        }
        return result;
    }

    public static void setServiceUrl(String serviceUrl) {
        HttpServiceClient.serviceUrl = serviceUrl;
    }

    public static String getServiceUrl() {
        return serviceUrl;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值