OkHttp是鼎鼎大名的Square公司开发的,这个公司在开源事业上面贡献良多,除了OkHttp之外,还开发了像Picasso、Retrofit等著名的开源项目。OkHttp不仅在接口封装上面做的简单易用,就连在底层实现上也是自成一派,比起原生的HttpURLConnection,可以说是有过之而无不及,现在已经成了广大Android开发者首选的网络通信库
一、在使用OkHttp之前,我们需要先在项目中添加OkHttp库的依赖,编辑app/buils.gradle文件,在dependencies闭包中添加如下内容:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.squareup.okhttp3:okhttp:3.2.0' //添加这行程序
}
二、布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:id="@+id/sendRequest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Request"/>
<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>
</RelativeLayout>
三、直接修改MainActivity中的代码
package com.example.yxp.httplcc;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.VoiceInteractor;
import android.os.Bundle;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.os.Handler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends Activity {
public static final int SHOW_RESPONSE=0;//用于更新操作
private Button sendRequest;
private TextView responseText;
//用于处理和发送消息的Hander
private Handler handler=new Handler(){
public void handleMessage(Message msg){
//如果返现msg.what=SHOW_RESPONSE,则进行制定操作,如想进行其他操作,则在子线程里将SHOW_RESPONSE改变
switch (msg.what){
case SHOW_RESPONSE:
String response=(String)msg.obj;
//进行UI操作,将结果显示到界面上
responseText.setText(response);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendRequest=(Button)findViewById(R.id.sendRequest);
responseText=(TextView)findViewById(R.id.responseText);
sendRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// sendRequestWithHttpURLConnection();
sendRequestwithOkHttp();
}
});
}
private void sendRequestwithOkHttp(){
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://www.baidu.com").build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
showResponse(responseData);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void sendRequestWithHttpURLConnection(){
//开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection=null;
try{
URL url=new URL("https://www.cnblogs.com/Liang-Blog/p/5760201.html");
connection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in=connection.getInputStream();
//下面对获取到的输入流进行读取
BufferedReader bufr=new BufferedReader(new InputStreamReader(in));
StringBuilder response=new StringBuilder();
String line=null;
while((line=bufr.readLine())!=null){
response.append(line);
}
Message message=new Message();
message.what=SHOW_RESPONSE;
//将服务器返回的数据存放到Message中
message.obj=response.toString();
handler.sendMessage(message);
}catch(Exception e){
e.printStackTrace();
}finally {
if(connection!=null){
connection.disconnect();
}
}
}
}).start();
}
private void showResponse(final String response){
runOnUiThread(new Runnable() {
@Override
public void run() {
responseText.setText(response);
}
});
}
}
实现效果