• Android使用HTTP协议访问网络——HttpClient


    套路篇

    1.HttpClient是一个接口,因此无法创建它的实例,通常情况下都会创建一个DefaultHttpClient的实例

    HttpClient httpClient=new DefaultHttpClient();

    2.如果想要发起一条GET请求,就创建一个HttpGet对象,并传入目标网络的对象,然后调用HtttpClient中的excute()方法:

    HttpGet httpGet=new HttpGet("http://www.baidu.com");
    HttpResponse httpResponse=httpClient.execute(httpGet);

    如果想发起一条POST请求会比GET复杂一点,首先创建一个HttpPost对象,并传入目标网址

    HttpPost httpPost=new HttpPost("http/:www.baidu.com");

    然后通过NameValuePair集合来存放待提交的数据,并将这个参数传入到一个UrlEncodedFormEntity中,然后调用HttpPost的setEntity()方法将构建好的UrlEncodedFormEntity传入

    List<NameValuePair> params=new ArrayList<NameValuePair>();
    
    params.add(new BasicNameValuePair("username","admin"));
    
    params.add(new BasicNameValuepair("password","123456"));
    
    UrlEncodeFormEntity entity=new UrlEncodeFormEntity(params,"utf-8");
    
    httpPost.setEntity(entity);

    接下来就和GET方法一样啦,httpClient.execute(httpPost);

    3.执行完execute()方法后会返回一个HttpResponse对象,服务器返回的数据都在里面,通常我们会先取出服务器返回的状态码,如果等于200,则说明请求响应成功

    if(httpResponse.getStatusLine().getStatueCode()==200){
    
      //请求和响应都成功了
    
    }

    4.读取服务器返回的具体内容,可以调用getEntity()访问获取到一个HttpEntity实例,然后调用EntityUtils.toString()这个静态类将HttpEntity转换成字符串

    HttpEntity entity=httpResponse.getEntity();

    String response=EntityUtils.toString(entity);

    如果返回的数据带有中文,转换的时候需要将字符集指定为utf-8

    String response=EntityUtils.toString(entity,"utf-8");

    实战篇

    MainActivity

    import android.os.Handler;
    import android.os.Message;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    
    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.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    
    public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    
        public static final int SHOW_RESPONSE=0;//用于更新操作
        private Button sendRequest_Button;
        private TextView responseText;
    
    
    
    
        //用于处理和发送消息的Handler
        private Handler handler=new Handler(){
            public void handleMessage(Message msg){
                switch (msg.what){
                    case SHOW_RESPONSE:
                        String response=(String)msg.obj;
                        responseText.setText(response);
                }
            }
        };
    
    
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            sendRequest_Button=(Button)findViewById(R.id.sendrequest);
            responseText=(TextView)findViewById(R.id.response_text);
            sendRequest_Button.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            if(v.getId()==R.id.sendrequest){
                sendRequestWithHttpClient();
            }
        }
    
        public void sendRequestWithHttpClient(){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try{
                        HttpClient httpClient=new DefaultHttpClient();
                        HttpGet httpGet=new HttpGet("http://www.baidu.com");
                        HttpResponse httpResponse=httpClient.execute(httpGet);
                        if(httpResponse.getStatusLine().getStatusCode()==200){
                            //请求和响应都成功了
                            HttpEntity entity=httpResponse.getEntity();
                            String response= EntityUtils.toString(entity, "utf-8");
    
                            Message message=new Message();
                            message.what=SHOW_RESPONSE;
                            //将服务器返回的结果保存到Message中
                            message.obj=response.toString();
                            handler.sendMessage(message);
    
                        }
    
                    }catch(Exception e){
    
                    }finally {
    
                    }
    
                }
            }).start();
    
        }
    
    }

    AndroidManifest

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

    Layout

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <Button
            android:id="@+id/sendrequest"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Send Request"/>
    
        <ScrollView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
    
            <TextView
                android:id="@+id/response_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </ScrollView>
    </LinearLayout>
  • 相关阅读:
    Android 布局中设置分割线
    程序员的创意爱情告白大法
    java中路径/和\的区别
    Oracle解锁表
    Android组件TextView细节
    android this,getApplication(),getApplicationContext()的区别
    ORA01013: user requested cancel of current operation
    Android自定义View之一:初探实例
    使用开源jabber(XMPP)协议及openfire架设内部即时通讯服务
    九、为ASP.NET MVC应用程序创建单元测试
  • 原文地址:https://www.cnblogs.com/Liang-Blog/p/5763408.html
Copyright © 2020-2023  润新知