先简单说一下HTTP协议,客户端向服务器发出一条HTTP请求,服务器收到请求会返回一些数据给客户端,然后客户端在对这些数据进行解析和处理就可以了。WebView控件,其实就是我们向百度服务器发起了一条HTTP请求,服务器分析出我们想要访问的是百度的首页,于是会把该网页的HTML代码进行返回,然后WebView再调用手机浏览器内核对返回的HTML代码进行解析。
使用HttpURLConnection
首先需要获取到HttpURLConnection的实例,一般只需new出一个URL对象,并传入目标的网络地址,然后调用一下openConnection()方法即可
URL url = new URL("http://www.baidu.com");
HttpURLConnection connection = (HttpURLConnection)uri.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()
实际操作:
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 = findViewById(R.id.send_request);
responseText= 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;
BufferedReader reader = null;
try {
URL url = new URL("https://www.baidu.com");
//注意这里的https!!!!!如果写http会出错误不安全,这里有坑
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
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() {
@Override
public void run() {
responseText.setText(response);
}
});
}
}
我们用点击事件开启了一个子线程,然后在子线程发出HTTP请求,接着利用BufferedReader对服务器返回的流进行读取,在shouResponse方法中调用runOnUiThread。因为Android是不允许在子线程进行UI操作的,所以要通过这个方法将线程切换到住线程再更新UI元素。
如果是提交数据给服务器,将HTTP请求方法改成POST,并在获取输入流之前把要提交的数据写出即可,注意每条数据都要以键值的形式存在,数据与数据之间用&风格开,比如我们要提交用户名密码。
connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");