Android中使用http协议访问网络

HTTP协议的工作原理:客户端向服务器端发送http请求,服务器端收到请求后返回一下数据给客户端,客户端接受消息并进行解析。

在Android中发送http请求的方式有两种,第一种是通过HttpURLConnection的方式,第二种是通过HttpClient的方式。

通过HttpURLConnection的方式发送http请求

通常分为以下5个步骤:

1.获取HttpURLConnection实例对象。先new一个URL实例,然后调用该对象的openConnection()方法。

2.设置http请求使用的方法(get和post方法,get方法是从服务器获取数据,post是向服务器发送数据)。

3.自由设定参数,如连接超时、读取超时等。

4.调用getInputStream()方法获取服务返回的信息。

5.调用disconnect()方法将http连接关闭。

 现在是简单实现的代码:

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
 3     android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
 4     android:paddingRight="@dimen/activity_horizontal_margin"
 5     android:paddingTop="@dimen/activity_vertical_margin"
 6     android:orientation="vertical"
 7     android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
 8     >
 9 
10     <Button
11         android:layout_width="match_parent"
12         android:layout_height="wrap_content"
13         android:id="@+id/send_request"
14         android:text="send request"
15 
16         />
17 
18     <ScrollView
19         android:layout_width="match_parent"
20         android:layout_height="match_parent">
21 
22         <TextView
23             android:layout_width="match_parent"
24             android:layout_height="wrap_content"
25             android:id="@+id/response"
26             android:hint="nihao,zhelixianshinierong"
27             />
28     </ScrollView>
29 
30 </LinearLayout>
activity_main.xml

这是Java代码

  1 package com.example.yqt.networktest;
  2 
  3 import android.os.Handler;
  4 import android.os.Message;
  5 import android.support.v7.app.AppCompatActivity;
  6 import android.os.Bundle;
  7 import android.view.Menu;
  8 import android.view.MenuItem;
  9 import android.view.View;
 10 import android.widget.Button;
 11 import android.widget.TextView;
 12 
 13 import java.io.BufferedReader;
 14 import java.io.InputStream;
 15 import java.io.InputStreamReader;
 16 import java.net.HttpURLConnection;
 17 import java.net.URL;
 18 
 19 public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 20 
 21     public static final int SHOW_RESPONSE = 0;
 22 
 23     Button sentRequestBtn;
 24     TextView responseText;
 25 
 26     Handler handler = new Handler() {
 27         @Override
 28         public void handleMessage(Message msg) {
 29 
 30             switch (msg.what){
 31                 case SHOW_RESPONSE:
 32 
 33                     String response = (String) msg.obj;
 34                     responseText.setText(response);
 35             }
 36             //super.handleMessage(msg);
 37 
 38         }
 39     };
 40 
 41     @Override
 42     protected void onCreate(Bundle savedInstanceState) {
 43         super.onCreate(savedInstanceState);
 44         setContentView(R.layout.activity_main);
 45 
 46         sentRequestBtn = (Button)findViewById(R.id.send_request);
 47         responseText = (TextView)findViewById(R.id.response);
 48 
 49         sentRequestBtn.setOnClickListener(this);
 50         
 51 
 52     }
 53 
 54 
 55     @Override
 56     public void onClick(View v) {
 57 
 58         if(v.getId() == R.id.send_request){
 59             sendRequestWithHttpURLConnection();
 60         }
 61 
 62     }
 63     private void sendRequestWithHttpURLConnection(){
 64         new Thread(new Runnable() {
 65             @Override
 66             public void run() {
 67                 HttpURLConnection connection = null;
 68                 try {
 69                     URL url = new URL("http://www.baidu.com");
 70                     connection = (HttpURLConnection) url.openConnection();
 71                     connection.setRequestMethod("GET");
 72                     connection.setConnectTimeout(8000);
 73                     connection.setReadTimeout(8000);
 74                     InputStream in = connection.getInputStream();
 75                     BufferedReader reader = new BufferedReader(new InputStreamReader(in));
 76                     StringBuilder response = new StringBuilder();
 77 
 78                     String line;
 79                     while ((line = reader.readLine()) !=null){
 80                         response.append(line);
 81                     }
 82 
 83                     Message message = new Message();
 84                     message.what = SHOW_RESPONSE;
 85                     message.obj = response.toString();
 86                     handler.sendMessage(message);
 87 
 88 
 89 
 90                 }catch (Exception e){
 91                     e.printStackTrace();
 92                 }finally {
 93                     if(connection != null){
 94                         connection.disconnect();
 95                     }
 96                 }
 97             }
 98         }).start();
 99     }
100 
101 
102 
103 }
mainactivity.java

通过HttpClient的方式发送http请求

HttpClient是Apache提供的http网络访问的接口。

1.创建一个DefaultHttpClient的实例

2.创建一个HttpGet对象,并传入目标网络地址,调用execute()方法。

3.获取返回码,判断连接是否成功。若成功,还可提取相应数据。

原文地址:https://www.cnblogs.com/yuqt/p/5080991.html