1.
在过去,Android上发送HTTP请求有一般两种方式:HttpURLConnection和HttpClient。不过在安卓6.0系统以后,HttpClient的功能已经被完全移除了。
所以本次只学习HttpURLConnection的用法。
①:获得HttpURLConnection的实例
URL url = new URL(“https://www.baidu.com”);
HttpURLConnection connection =(HttpURLConnection)url.openConnection();
②获取到实例后,可以设置一下HTTP请求所使用的方法。
GET:表示希望从服务器获得数据。该请求的数据会附在URL之后,通过?来拼接所传的参数,参数之间以&相连。
POST:表示提交数据给服务器。该请求的参数不是放在URL字符串里,而是放在HTTP请求的正文中,请求的数据被封装起来以流的形式发送给服务器。
一般默认的请求为GET。
connection.setRequestMethod(“GET”);
③接下来可以进行一些自由的定制了,常用属性如下:
connection.setConnectTimeout(); //设置连接超时时间
connection.setReadTimeout(); //设置读取超时时间
connection.setRequestProperty(); //设置请求头参数
connection.setDoOutput(); //设置是否向HttpURLConnection输出,对于POST请求,参数要放在http正文中,因此需要设为true,默认情况为false
connection.setDoInput(); //设置是否从HttpURLConnection读入,默认情况为true
④调用connect()连接远程资源
通过connect()方法就与服务器建立了Sockect连接,连接以后,连接属性就不可以再修改了。然后可以查询服务器返回的头信息了。
connection.getResponseCode();//获取服务器的响应代码,请求成功的代码一般为200.
connection.getResponseMessage();//获取服务器的响应消息
⑤调用getInputStream()方法获取服务器返回的输入流,然后对输入流进行读取。
InputStream input = connection.getInputStream(); //得到响应流
BufferedReader reader = new BufferedReader(new InputStreamReader(input));//构建BufferedReader对象
StringBuilder sb = new StringBuilder();//构建StringBuilder对象
String line = null;
while ((line=reader.readLine())!=null){ //读取输入流中的数据
sb.append(line);
}
⑥最后调用disconnect()方法将这个http关掉。
connection.disconnect();
⑦将请求到的服务器数据显示到界面上。
实战:
访问百度,并将返回的数据显示到屏幕上。
页面布局代码直接贴上来了:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HttpActivity">
<Button
android:id="@+id/btn_sendRequest"
android:text="发送请求"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/responseText"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</ScrollView>
</LinearLayout>
效果图如下:

我们需要点击”发送请求“按钮后,服务器返回的数据在下方显示出来。
以下为逻辑代码:
package com.kotlin.activitystudy;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
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.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class HttpActivity extends AppCompatActivity {
private Button btn_Request;
private TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http);
btn_Request = findViewById(R.id.btn_sendRequest);
responseText = findViewById(R.id.responseText);
btn_Request.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendRequestWithHttpURLConnection();
}
});
}
private void sendRequestWithHttpURLConnection(){
//开启线程发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("https://www.baidu.com");
connection =(HttpURLConnection)url.openConnection();
//通过此方法创建的HttpURLConnection对象,并没有真正执行连接操作,只是创建了一个新的实例,在正式连接前,往往还需要设置一些属性,如连接超时和请求方式等
connection.setRequestMethod("GET"); //设置请求方式
connection.setConnectTimeout(8000);//设置连接超时时间
connection.setReadTimeout(8000);//设置读取超时时间
connection.connect();//连接远程资源
Log.d("httpActivity","服务器的响应代码==》"+connection.getResponseCode());//可查看响应代码是否为200,是则请求成功,否则请求失败
InputStream input = connection.getInputStream();//获取到服务器返回的响应流
BufferedReader reader = new BufferedReader(new InputStreamReader(input));//构建BufferedReader用于读取响应流
StringBuilder sb = new StringBuilder();//构建StringBuilder对象,用来接收BufferedReader中的数据
String line = null;
while ((line=reader.readLine())!=null){
sb.append(line);
}
showResponse(sb.toString()); //调用showResponse方法,将StringBuilder中的内容显示到Activity中
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
connection.disconnect(); //关闭该http
}
}
}).start();
}
private void showResponse(String sb){
runOnUiThread(new Runnable() { //Android不允许在子线程中更新ui,这里使用异步消息处理机制中的工作原理更新ui
@Override
public void run() {
responseText.setText(sb);
}
});
}
}
运行结果如下:


okk,至此,我们通过HttpURLConnection的方法就拿到服务器返回的数据了。
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/289504.html