Android中使用http协议访问网络

时间:2023-03-08 15:04:38
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连接关闭。

现在是简单实现的代码:

 <LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
> <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/send_request"
android:text="send request" /> <ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"> <TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"
android:hint="nihao,zhelixianshinierong"
/>
</ScrollView> </LinearLayout>

activity_main.xml

这是Java代码

 package com.example.yqt.networktest;

 import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
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; Button sentRequestBtn;
TextView responseText; Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) { switch (msg.what){
case SHOW_RESPONSE: String response = (String) msg.obj;
responseText.setText(response);
}
//super.handleMessage(msg); }
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); sentRequestBtn = (Button)findViewById(R.id.send_request);
responseText = (TextView)findViewById(R.id.response); sentRequestBtn.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 reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder(); String line;
while ((line = reader.readLine()) !=null){
response.append(line);
} Message message = new Message();
message.what = SHOW_RESPONSE;
message.obj = response.toString();
handler.sendMessage(message); }catch (Exception e){
e.printStackTrace();
}finally {
if(connection != null){
connection.disconnect();
}
}
}
}).start();
} }

mainactivity.java

通过HttpClient的方式发送http请求

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

1.创建一个DefaultHttpClient的实例

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

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