Android 中HttpClient请求和HttpURLConnect请求

MainActivity:

package animtest.com.example.e531.week1_09month;


import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Button btnClient= (Button) findViewById(R.id.btn_client);
        Button btnUrl= (Button) findViewById(R.id.btn_url);
        ListView listView= (ListView) findViewById(R.id.lv);


        btnClient.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //执行异步任务
                MyTask myTask=new MyTask();
                myTask.execute(new String[]{"https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10","1"});

            }
        });


        btnUrl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //执行异步任务
                MyTask myTask=new MyTask();
                myTask.execute(new String[]{"https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10","2"});
            }
        });


    }


    class MyTask extends AsyncTask<String,Void,String>{


        @Override
        protected String doInBackground(String... params) {
            String resultStr="";


            //得到请求的类型
            String type=params[1];
            if("1".equals(type)){//如果是"1" 执行 HttpGet请求
            //因为请求的是https协议的网址,eclipse下使用HttpGet请求会报错,需要添加以下这行代码
            SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
            //1.创建一个HttpClient对象
            HttpClient hc=new DefaultHttpClient();
            //2.创建httpGet对象
            HttpGet hg=new HttpGet(params[0]);


            try {
                //3.执行请求
                HttpResponse response=hc.execute(hg);


                //4.判断结果码
                int code=response.getStatusLine().getStatusCode();
                if(code==200){
                    //5.得到请求的结果
                    HttpEntity result=response.getEntity();


                    resultStr="client请求:"+EntityUtils.toString(result);
                }


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


            }else if("2".equals(type)){//如果是2执行 HttpUrlConnection请求


                try{
                    //1.创建Url对象
                    URL url=new URL(params[0]);
                    //2.打开连接
                    HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                    //3.设置
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(5000);


                    //4.得到响应码,进行判断
                    int code=connection.getResponseCode();
                    if(code==200){
                        //5.得到结果
                        InputStream inputStream=connection.getInputStream();
                        resultStr= "url请求:"+streamToString(inputStream);




                    }



                }catch(Exception ex){
                    ex.printStackTrace();
                }


            }else{


            }


            return resultStr;
        }


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);


            Log.d("zzz",s);
        }


        @Override
        protected void onPreExecute() {
            super.onPreExecute();


        }
    }


    public String streamToString(InputStream stream){
        StringBuilder builder=new StringBuilder();
        try{
            BufferedReader br=new BufferedReader(new InputStreamReader(stream,"utf-8"));
            String con;
            while((con=br.readLine())!=null){
                builder.append(con);
            }


        }catch (Exception ex){
            ex.printStackTrace();
        }


        return builder.toString();
    }
}
activity_main:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="animtest.com.example.e531.week1_09month.MainActivity">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HttpClient请求"
        android:id="@+id/btn_client"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HttpURLConnect请求"
        android:id="@+id/btn_url"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />


    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/lv"
        android:layout_below="@+id/btn_client"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>


    



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值