Android使用Http协议访问网络——HttpConnection

来源:互联网 发布:猪八戒那个是什么软件 编辑:程序博客网 时间:2024/05/19 13:20
套路篇

使用HttpConnection访问网络一般有如下的套路:

1.获取到HttpConnection的实例,new出一个URL对象,并传入目标的网址,然后调用一下openConnection()方法。

1 HttpURLConnection connection=null;2 URL url=new URL("http://www.baidu.com");3 connection=(HttpURLConnection)url.openConnection();

2.得到了HttpConnection的实例后,设置请求所用的方法(GET:从服务器获取数据,POST:提交数据给服务器)

connection.setRequestMethod("GET");或
connection.setRequestMethod("POST");

3.自由定制的环节(设置连接超时,读取的毫秒数,以及服务器希望得到的消息头等)

 connection.setConnectTimeout(8000); connection.setReadTimeout(8000);

4.利用getInputStream()方法获取服务器的返回的输入流,然后读取

InputStream in=connection.getInputStream();//下面对获取到的输入流进行读取BufferedReader bufr=new BufferedReader(new InputStreamReader(in));StringBuilder response=new StringBuilder();String line=null;while((line=bufr.readLine())!=null){          response.append(line);}

5.调用disconnect()方法将HTTP连接关闭掉

 if(connection!=null){     connection.disconnect(); }

实战篇

新建一个Android工程

1.activity_main.xml(里面有一个Button和一个TextView)

<?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/send_request"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Send Request" />    <ScrollView        android:layout_width="match_parent"        android:layout_height="match_parent">        <TextView            android:id="@+id/response_text"            android:layout_width="match_parent"            android:layout_height="wrap_content" />    </ScrollView></LinearLayout>

2.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 java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;public class MainActivity extends AppCompatActivity implements View.OnClickListener {    public static final int SHOW_RESPONSE=0;//用于更新操作    private Button sendRequest;    private TextView responseText;    //用于处理和发送消息的Hander    private Handler handler=new Handler(){        public void handleMessage(Message msg){            //如果返现msg.what=SHOW_RESPONSE,则进行制定操作,如想进行其他操作,则在子线程里将SHOW_RESPONSE改变            switch (msg.what){                case SHOW_RESPONSE:                    String response=(String)msg.obj;                    //进行UI操作,将结果显示到界面上                    responseText.setText(response);            }        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        sendRequest=(Button)findViewById(R.id.send_request);        responseText=(TextView)findViewById(R.id.response_text);        sendRequest.setOnClickListener(this);    }    @Override    public void onClick(View v) {        if(v.getId()==R.id.send_request){            sendRequestWithHttpURLConnection();        }    }    private void sendRequestWithHttpURLConnection(){        //开启线程来发起网络请求        new Thread(new Runnable() {            @Override            public void run() {                HttpURLConnection connection=null;                try{                    URL url=new URL("http://www.baidu.com");                    connection=(HttpURLConnection)url.openConnection();                    connection.setRequestMethod("GET");                    connection.setConnectTimeout(8000);                    connection.setReadTimeout(8000);                    InputStream in=connection.getInputStream();                    //下面对获取到的输入流进行读取                    BufferedReader bufr=new BufferedReader(new InputStreamReader(in));                    StringBuilder response=new StringBuilder();                    String line=null;                    while((line=bufr.readLine())!=null){                        response.append(line);                    }                    Message message=new Message();                    message.what=SHOW_RESPONSE;                    //将服务器返回的数据存放到Message中                    message.obj=response.toString();                    handler.sendMessage(message);                }catch(Exception e){                    e.printStackTrace();                }finally {                    if(connection!=null){                        connection.disconnect();                    }                }            }        }).start();    }}

3.AndroidManifest.xml中注册权限

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

好,这个简单的例子就弄完了,接下来就看看效果吧。

这样我们就可以看到服务器返回给我们的数据了。

阅读全文
0 0