对HttpClient的理解

HttpClient 架包下载地址


对HttpClient的理解_第1张图片


get post请求 可以看到用httpClient 进行post get 请求是相对代码量少些,但是最新的的android studio不怎么支持它,解决方法可以用




但是这里又会出现一个问题  HttpClients所属的架包没有得到解决,(httpclients应该是最新apache所用的方法,如果用以前的老方法进行get post请求不用httpClients就可以必避免这个问题,把下载的包都放入libs目录中又会报一些错误,总之google对Apache支持不是很好,用android studio工具开发的话慎用apache httpclient,eclipse开发的话就要顺利很多。)

package com.example.pc.httpconnectiontest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

*
 * Created by pc on 2016/4/19.
 

public class HttpClientUtils {

    public static void main(String [] arges  ){

        HttpClientUtils.httpClientPost();

    }


    public static void httpClientGet(){


        HttpClient client = HttpClients.createDefault();

        HttpGet get = new HttpGet("http://baidu.com");

        try {



           HttpResponse response = client.execute(get);
            HttpEntity entity  = response.getEntity();
           String result =  EntityUtils.toString(entity,"UTF-8");

            System.out.println(result);


        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public static void httpClientPost(){

        HttpClient client = HttpClients.createDefault();

        HttpPost post = new HttpPost("http://fanyi.youdao.com/openapi.do");

        try {

            //设置post的参数

            List<BasicNameValuePair> parameters = new ArrayList<>();
            parameters.add(new BasicNameValuePair("keyfrom","zhanghappyzq"));
            parameters.add(new BasicNameValuePair("key","301249901"));
            parameters.add(new BasicNameValuePair("type","data"));
            parameters.add(new BasicNameValuePair("doctype","xml"));
            parameters.add(new BasicNameValuePair("version","1.1"));
            parameters.add(new BasicNameValuePair("q","congratulation"));
            post.setEntity(new UrlEncodedFormEntity(parameters,"UTF-8"));

            //post请求
            HttpResponse response = client.execute(post);
            HttpEntity entity  = response.getEntity();
            String result =  EntityUtils.toString(entity, "UTF-8");

            System.out.println(result);


        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}


你可能感兴趣的:(httpclient)