使用HttpURLConnection和使用OkHttp来进行网络访问
1. HttpURLConnection
使用HttpUrlConnection首先需要获取到它的实例,一般来说只需要new一个URL对象,并传入目标的网络地址,然后调用openConnection()方法即可,如:
URL url = new URL("https://baidu.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
得到实例之后设置Http的请求方式,也就是GET和POST,比如说GET:
connection.setRequestMethod("GET");
如果是POST,只需要将Http的请求方法改成POST,并在获取输入流之前把要提交的数据写出来就好了,这里每条数据都要以键值对的形式存在,数据与数据之间以 & 隔开,比如向服务器提交用户名和用户密码的POST请求:
connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
output.writeBytes("username=admin&password=1234");
然后可以设置一些其他的东西,比如连接超时设置、读取超时的毫秒数等。
之后就可以调用getInputStream()获取服务器返回的输入流了,
InputStream in = connection.getInputStream();
接下来就是对获取到的输入流进行读取了,这里使用BufferedReader对服务器返回的流进行读取:
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readline()) != null) {
response.append(line);
}
最后可以调用disconnect()方法将这个Http关闭:
connection.disconnection();
完整代码如下:
public class MainActivity extends AppCompatActivity {
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
Button sendRequest = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.text);
sendRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (view.getId() == R.id.button)
sendRequestWithHttpURLConnection();
}
});
}
public void sendRequestWithHttpURLConnection() {
// 开启线程
new Thread(new Runnable() {
@Override
public void run() {
HttpsURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL("https://www.baidu.com");
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
// 对获取的输入流进行读取
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
showResponse(builder.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) {
// 将线程切回主线程,更新UI
runOnUiThread(new Runnable() {
@Override
public void run() {
text.setText(response);
}
});
}
}
效果如下:
使用OkHttp
使用OkHttp首先需要在项目中添加OkHttp的依赖库,现在最新的版本是3.6.0
compile 'com.squareup.okhttp2:okhttp:3.6.0'
OkHttp的功能有很多,这里先学习他的基本的功能,实现和上面HttpURLConnection一样的功能。
直接上代码吧,解释写在注释里:
private void sendRequestWithOkHttp() {
new Thread(new Runnable() {
@Override
public void run() {
try {
// 首先创建一个OkHttp的实例
OkHttpClient client = new OkHttpClient();
// 创建一个Request对象,这是发起一条HTTP请求的前提
Request request = new Request.Builder()
.url("https://baidu.com")
.build();
// 调用OkHttpClient的newCall()方法来创建一个Call对象,并调用它的execute方法
// 来发送请求并获取服务器返回的数据
Response response = client.newCall(request).execute();
String responseDate = response.body().string();
showResponse(responseDate);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
上面是使用了“GET”方法,如果是需要使用“POST”,那么需要首先构造一个RequestBody对象来存放待提交的参数:
RequestBody requestBody = new FormBody.Builder()
.add("username", "admin")
.add("password", "1234")
.build();
然后在Request.Builder()方法中调用post()方法就好了
Request request = new Request.Builder()
.url("https://baidu.com")
.post(requestBody)
.build();