1、HTTP工作原理:客户端向服务器发出一条HTTP请求,服务器收到请求之后会返回一些数据给客户端,然后客户端在对这些数据进行解析和处理就可以了。从WebView的用法中其实也就是我们向百度服务器发送一条HTTP请求,接着WebView再调用手机浏览器内核对返回的HTML代码进行解析,最终将页面展现出来,不过WebView已经在后台帮我们处理好了发送HTTP请求、接受服务器响应、解析返回数据以及最终页面展示这几步工作。
首先我们需要获取到HttpURLConnection的实例,一般只需new出一个URL对象,并传入目标网络地址,然后调用一下openConnection()方法即可,如下所示:
URL = url = new URL("http://www.baidu.com");
HttpURLConnection connection = (HTTPURLConnection)url.openConnection();
在得到了HTTPURLConnection的实例之后,我们可以设置一下HTTP请求所使用的方法。常用的有两种:GET和POST.GET表示希望从服务器那里获得数据,而POST则表示希望提交数据给服务器。写法如下:
connection.setRequestMethod("GET");
接下来就可以进行一些自由定制了,比如设置连接超时,读取超时毫秒数,以及服务器希望得到的一些消息头等。这部分内容根据自己的实际情况进行编写,实例方法如下:
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
之后在调用getInputStream()方法就可以获取到服务器返回的输入流了,剩下的就是对输入流进行读取,如下所示:
InputStream in = connection.getInputStream();
最后可以调用disconnect()方法将这个HTTP连接关闭掉,如下所示:
connection.disconnect();
下面进行项目实战
main.xml<?xml version="1.0" encoding="utf-8"?>
<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: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>
代码分析:这里我们使用了一个新的控件ScrollView,以滚动的形式查看屏幕外的那部分内容,布局中还放置了一个Button和一个TextView,Button用于发送HTTP请求,TextView用于将服务器返回的数据显示出来。
MainActivity.java
package com.example.administrator.httpurlconnection;
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.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button 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();//调用
sendRequestWithHttpURLConnection()方法
}
}
private void sendRequestWithHttpURLConnection() {
//开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader reader = null;
try{
URL url = new URL("https://www.baidu.com");//请求目标地址百度首
页
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
//下面对获取到的输入流进行读取
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null){
response.append(line);
}
showResponse(response.toString());
}catch (Exception e){
e.printStackTrace();
}finally {
if (reader != null){
try{
reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (connection != null){
connection.disconnect();
}
}
}
}).start();
}
private void showResponse(final String response) {
runOnUiThread(new Runnable() {//你明磊参数进行操作,将返回的数据进行读取,并
将结果传入到了showResponse()方法中,将线程切换到主线程,然后将更新UI元素
@Override
public void run() {
//在这里进行UI操作
responseText.setText(response);
}
});
}
}
注意:申明网络权限 <uses-permission android:name="android.permission.INTERNET"/>