HttpURLConnection
进行网络操作需要权限 : <uses-permission android:name="android.permission.INTERNET"/>
//开启线程来发起网络请求
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();
//获取HttpURLConnection实例后可以设置HTTP请求所使用的方法.
//一般有两种,GET(从服务器获取数据)和POST(提交数据给服务器)
connection.setRequestMethod("GET");
//设置连接超时
connection.setConnectTimeout(8000);
//设置读取超时
connection.setReadTimeout(8000);
/*如何需要提交数据则需要将setRequestMethod()改为post
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes("username=admin&password=123456");
*/
//获取服务器返回到我们内存的输入流.
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 (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭HTTP连接
connection.disconnect();
}
}
}).start();
}
private void showResponse(final String s) {
//由于android不允许再子线程进行UI操作的,我们可以通过这个方法将线程切换到主线程.,然后再更新UI元素.
runOnUiThread(new Runnable() {
@Override
public void run() {
//把数据显示到responseText视图.
responseText.setText(s);
}
});
}
}
OkHttp
使用前需要添加OkHttp库的依赖 : implementation 'com.squareup.okhttp3:okhttp:3.4.1'
进行网络操作需要权限 : <uses-permission android:name="android.permission.INTERNET"/>
new Thread(new Runnable() {
@Override
public void run() {
//创建OkHttpClient实例
OkHttpClient client = new OkHttpClient();
/*如果要发起一条HTTP请求,就需要创建一个Request对象,
我们可以在build()方法前连缀很多其他的方法来丰富这个
request对象.*/
Request request = new Request.Builder()
.url("https://www.baidu.com")
.build();
try {
/*OkHttpClient对象的newCall()方法可以创建一个Call对象,
execute()方法用来发送请求并获取服务器返回的数据,execute()是
同步方法,必须放在子线程中执行,此外有个enqueue()方法,此方法是异步方法,会自己开一条子线程*/
Response response = client.newCall(request).execute();
//处理数据
String responseData = response.body().string();
//调用方法显示数据
showResponse(responseData);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
以上代码是GET,以下是POST
//POST数据需要先构建一个RequestBody对象来存放待提交的参数(数据).
RequestBody requestBody = new FormBody.Builder()
.add("username" , "admin")
.add("password" , "123456")
.build();
//然后利用post方法把RequestBody对象存入.
Request request1 = new Request.Builder()
.url("https://www.baidu.com")
.post(requestBody)
.build();
//其他代码跟GET一样
enqueue()方法用法:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.baidu.com")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//针对异常情况处理
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//处理服务器放回的具体数据
String responseData = response.body().string();
showResponse(responseData);
}
});
---------------------
作者:Heawill
来源:CSDN
原文:https://blog.csdn.net/Krehizi/article/details/83044293
版权声明:本文为博主原创文章,转载请附上博文链接!