Http的两种请求方式:HttpClient和HttpUrlConnection

这篇博客对比了Android中HttpClient和HttpURLConnection两种HTTP请求方式。HttpClient在Android 6.0后被弃用,适合2.2版本及以前,而HttpURLConnection在2.3版本后成为首选。文中以POST请求为例,详细介绍了使用HttpClient和HttpURLConnection进行网络请求的步骤,包括引入库、设置参数、创建请求、处理响应等。

在这里记录一下两种Http请求方式,建立个模板方便自己以后学习和使用。

HttpClient

这种请求方式在Android6.0版本直接删除了,这种方式在Android2.2版本之前使用比较合适,2.3版本之后比较适合HttpUrlConnection。下面以POST方式为例
第一步:需要在build.gradle引进类库

android{
		useLibrary 'org.apache.http.legacy'
		}

第二步:通过DefaultHttpClient类来实例化HttpClient,并设置好默认参数(这一部分可以直接用)

private HttpClient createHttpClient() {
        HttpParams httpParams = new BasicHttpParams();
        //设置连接超时
        HttpConnectionParams.setConnectionTimeout(httpParams,15000);
       //设置请求超时        HttpConnectionParams.setSoTimeout(httpParams,15000);
        HttpConnectionParams.setTcpNoDelay(httpParams,true);

        //设置HTTP版本,和字符形式
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);

        //持续握手
        HttpProtocolParams.setUseExpectContinue(httpParams,true);
        
        //通过DefaultHttpClient类来实例化HttpClient
        return new DefaultHttpClient(httpParams);
    }

第三步:创建HttpPost请求,传递网络参数,并对返回结果进行相应处理

private void useHttpClientPost(String url){
        //Post请求添加API地址
        HttpPost mhttpPost = new HttpPost(url);
        //头部请求
        mhttpPost.addHeader("Connection","Keep-Alive");

        try {
            //获取httpClient
            HttpClient httpClient = createHttpClient();
            List<NameValuePair> postParams = new ArrayList<>();
            //传递的参数,用的时淘宝的ip库
            postParams.add(new BasicNameValuePair("ip","ip地址"));
            mhttpPost.setEntity(new UrlEncodedFormEntity(postParams));
            //获取的返回信息
            HttpResponse httpResponse = httpClient.execute(mhttpPost);
            //获得其字符流
            HttpEntity httpEntity = httpResponse.getEntity();
            int code = httpResponse.getStatusLine().getStatusCode();
            if(httpEntity != null){

                /*  将其字符流转化为json格式,再通过gson转为为数据类
                JSONObject jsonObject = new JSONObject(EntityUtils.toString(httpEntity));
                info infos = new Gson().fromJson(jsonObject.toString(),info.class);
                Log.i(TAG, "请求码codes:"+infos.getCode());
                */
                
                //直接利用字符流输出字符串,结果并不是数组集,而是字符串
                InputStream inputStream = httpEntity.getContent();
                //处理字符流
                String response = converStreamToString(inputStream);
                Log.d(TAG, "请求码:"+code+"\n请求结果:\n"+response);
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }/*catch (JSONException e) {
            e.printStackTrace();
        }*/
    }

这是上面处理字符流的方法

private String converStreamToString(InputStream is) throws IOException{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuffer sb = new StringBuffer();
        String line = null;
        while((line = reader.readLine()) != null){
            sb.append(line+"\n");
        }
        String respose = sb.toString();
        return respose;
    }

(关于GET请求就不需要发送一些参数等,直接获取数据,因此可以去要List这个放入键对参数)

第四步:就直接开启线程获取数据

new Thread(new Runnable() {
                    @Override
                    public void run() {
                        useHttpClientGet("http://ip.taobao.com/service/getIpInfo.php");
                    }
                }).start();

结果如下:
在这里插入图片描述

HttpURLConnection

2.3版本之后比较适合HttpUrlConnection。下面以POST方式为例
HttpURLConnection的请求设置都基本不变,所以可以将一些方法放入到ConnManager类里面进行统一管理
第一步:设置默认参数,如连接超时时间等

//给URLConnection设置默认参数,模板
    public static HttpURLConnection getHttpURLConnection(String url){
        HttpURLConnection httpURLConnection = null;
        try {
            URL mUrl = new URL(url);
            httpURLConnection = (HttpURLConnection) mUrl.openConnection();
            //设置连接超时时间
            httpURLConnection.setConnectTimeout(5000);
            //设置读取超时时间
            httpURLConnection.setReadTimeout(5000);
            //设置请求方式
            httpURLConnection.setRequestMethod("POST");
            //设置Header
            httpURLConnection.setRequestProperty("Connection","Keep-Alive");
            //接受输入流,即接受服务器传来的数据,默认要设置为true
            httpURLConnection.setDoInput(true);
            //传递参数时,需要开启,GET请求用不到传递参数,因此可以设置为false
            httpURLConnection.setDoOutput(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return httpURLConnection;
    }

第二步:输出传递的参数,放入方法里面进行统一管理

//Post请求需要输出参数,GET不需要这方法,模板
    public static void postParams(List<NameValuePair> paramsList, OutputStream outputStream) throws  IOException{
        StringBuilder stringBuffer = new StringBuilder();
        for(NameValuePair pair: paramsList){
            if(!TextUtils.isEmpty(stringBuffer)){
                stringBuffer.append("&");
            }
            stringBuffer.append(URLEncoder.encode(pair.getName(),"UTF-8"));
            stringBuffer.append("=");
            stringBuffer.append(URLEncoder.encode(pair.getValue(),"UTF-8"));
        }
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
        bufferedWriter.write(stringBuffer.toString());
        bufferedWriter.flush();
        bufferedWriter.close();
    }

第三步:创建HttpURLConnection

private void urlHttpConnectionPost(String url){
        InputStream inputStream = null;
        HttpURLConnection connection = ConnManager.getHttpURLConnection(url);
        try {
            List<NameValuePair> list = new ArrayList<>();
            list.add(new BasicNameValuePair("ip","你的ip地址"));
            ConnManager.postParams(list,connection.getOutputStream());
            connection.connect();
            inputStream = connection.getInputStream();
            int code = connection.getResponseCode();
            String response = converStreamToString(inputStream);
            Log.d(TAG, "请求码:"+code+"\n请求结果:\n"+response);
            inputStream.close();
            /*若想要转化为json格式,则可以
	         *JSONObject jsonObject = new JSONObject(response.tostring());
	         *info infos = new Gson().fromJson(jsonObject.toString(),info.class);
	         *Log.i(TAG, "请求码codes:"+infos.getCode());*/
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

输入流处理方法converStreamToString在上面有
第四步:开启线程,进行网络请求

new Thread(new Runnable() {
                    @Override
                    public void run() {
                        urlHttpConnectionPost("http://10.0.0.2/test3/test_api.php");
                    }
                }).start();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值