使用OkHttp(以这个为主!!)
OkHttp是广大Android开发者首选的网络通信库.
OkHttp使用五部曲:
1.使用OkHttp时首先需要在项目中添加对OkHttp库的依赖,编辑app/build.gradle文件,在dependencies闭包中添加如下内容:implementation'com.squareup.okhttp3:okhttp:3.10.0' 当然闭包可能不同,我们只需要在网站https://github.com/square/okhttp将最新的闭包导入即可,不要忘记添加完之后更新一下.添加完上述依赖之后会自动下载两个库,一个是OkHttp库,一个是Okio库,后者是前者的通信基础
2.首先创建一个OkHttpClient实例,(Client是代理人的意思)
OkHttpClient client=new OkHttpClient();
3.创建一个Request对象来发起一条HTTP请求(可以在build()方法之前连缀很多的方法来丰富这个Request对象,比如通过url()方法来设置目标的网络地址)
Request request=new Request.Builder().url("https://www.taobao.com").build();
4.调用OkHttpClient的newCall()方法来创建一个Call对象,并调用它的execute()方法来发送请求并获取服务器返回的数据,其中Response对象就是服务器返回的数据了.
Response response=client.newCall(request).execute();
5.通过如下写法来返回具体的内容
String responseData=response.body().string();
如果发送一条POST请求会比GET请求稍微复杂一些,需要先构造一个RequestBody对象来存放待提交的数据
RequestBodyrequestBody=new FormBody().Builder.add("username","admin").
add("password","123456").build();
然后再Request.Builder中调用一下post()方法,并将RequestBody对象传入:
Requestrequest=new Request().Builder().url("http://www.baidu.com").post(requestBody).build;
接下来的操作便和GET请求一样了,调用execute()方法来发送请求并获取服务器返回的数据即可
附开发源码
public class MainActivityextends AppCompatActivityimplements View.OnClickListener {
private ButtonmBtnSendrequest;
private TextViewmTvResponse;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtnSendrequest=findViewById(R.id.send_request);
mTvResponse=findViewById(R.id.response_text);
mBtnSendrequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.send_request:
//具体实现业务
sendRequestWithOkHttp();
break;
}
}
private void sendRequestWithOkHttp() {
new Thread(new Runnable() {
@Override
public void run() {
try {
//首先创建一个OkHttpClient实例,Client是代理人的意思
OkHttpClient client=new OkHttpClient();
//创建一个request对象来发起一条HTTP请求
Request request=new Request.Builder().url("https://www.taobao.com").build();
// RequestBody requestBody=new FormBody().Builder.add("username","admin").
// add("password","123456").build();
// Request request=new Request().Builder().url("http://www.baidu.com").post(requestBody).build;
//创建一个Call对象,并调用它的execute()方法来发送请求并获取服务器返回的数据
Response response=client.newCall(request).execute();
String responseData=response.body().string();
showResponse(responseData);
}catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void showResponse(final String response){
runOnUiThread(new Runnable() {
@Override
public void run() {
mTvResponse.setText(response);
}
});
}
}
使用HttpURLConnection
首先需要获取HttpURLConnection的实例,一般new出一个URL对象并传入目标的网络地址,然后调用一下openConnection()方法即可
URL url=new URL("https://www.baidu.com");
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
在获取了HttpURLConnection的实例之后,我们可以设置一下HTTP请求所用的方法.通常用的方法有GET和POST.前者表示希望从服务器那里获取数据,后者表示希望提交数据给服务器.
httpURLConnection.setRequestMethod("GET");
然后可以进行一些自由定制,比如设置链接超时,读取超时的毫秒数,以及服务器希望得到的一些消息头等
httpURLConnection.setConnectTimeout(8000);
httpURLConnection.setReadTimeout(8000);
调用getInputStream()方法可以获取服务器返回的输入流,然后的任务是对输入流进行读取.(对输入流进行读取时我们通常要对输入流进行处理,将InputStream包装成缓冲流)
InputStream inputStream=httpURLConnection.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
最后调用disconnect()方法将这个HTTP连接关掉
httpURLConnection.disconnect();
源码如下
public class MainActivityextends AppCompatActivityimplements View.OnClickListener{
private ButtonmBtnSendrequest;
private TextViewmTvResponse;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtnSendrequest=findViewById(R.id.send_request);
mTvResponse=findViewById(R.id.response_text);
mBtnSendrequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.send_request:
//luojidaima
sendRequestWithHttpURLConnection();
break;
}
}
private void sendRequestWithHttpURLConnection(){
//kaiqixinxiancheng
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection httpURLConnection=null;
BufferedReader bufferedReader=null;
try {
URL url=new URL("https://www.baidu.com");
httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(8000);
httpURLConnection.setReadTimeout(8000);
InputStream inputStream=httpURLConnection.getInputStream();
//xiamianduihuoqudaodeshuruliujinxingduqu
bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
StringBuilder response=new StringBuilder();
String line;
while((line =bufferedReader.readLine())!=null){
response.append(line);
}
//
showResponse(response.toString());
}catch (IOException e) {
e.printStackTrace();
}finally {
if (bufferedReader!=null){
try {
bufferedReader.close();
}catch (IOException e) {
e.printStackTrace();
}
}
if (httpURLConnection!=null)
{
httpURLConnection.disconnect();
}
}
}
}).start();
}
private void showResponse(final String response){
runOnUiThread(new Runnable() {
@Override
public void run() {
//zaizhelizhixingUIcaozuo,jiangjieguoxianshidaojiemianshang
mTvResponse.setText(response);
}
});
}
}
上面中方法中都不要忘了在androidManifest.xml中声明网络权限.
<uses-permission android:name="android.permission.INTERNET"/>
网友评论