听说okhttp很好用,所以决定尝尝香
国际惯例:先上效果图
(okhttp使用get访问www.baidu.com)
在项目中使用okhttp的方法:
在github中找到okhttp当前的版本,okhttp地址:https://github.com/square/okhttp
复制上面的红色圈的代码到项目的build.gradle中
这样我们就可以在我们的项目中使用okhttp了
具体操作:
1,创建一个项目
2,引入okhttp:按上面的做法引入okhttp
3,使用okhttp(直接看代码),在布局中有一个按钮和一个文本,当我们点击按钮的时候,进行get请求,请求成功就把网络访问返回的数据设置到文本上面
layout布局:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/bt" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="get请求" /> <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
java代码:
public class MainActivity extends AppCompatActivity { private Button button; private TextView textView; public String string; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.bt); textView = (TextView) findViewById(tv); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //1.okhttpClient对象 OkHttpClient okHttpClient = new OkHttpClient(); //2构造Request, //builder.get()代表的是get请求,url方法里面放的参数是一个网络地址 Request.Builder builder = new Request.Builder(); Request request = builder.get().url("http://www.baidu.com/").build(); //3将Request封装成call Call call = okHttpClient.newCall(request); //4,执行call,这个方法是异步请求数据 call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { //失败调用 Log.e("MainActivity", "onFailure: " ); } @Override public void onResponse(Call call, final Response response) throws IOException { //成功调用 Log.e("MainActivity", "onResponse: " ); //获取网络访问返回的字符串 string = response.body().string(); runOnUiThread(new Runnable() { @Override public void run() { textView.setText(string); } }); } }); } }); } }
如此:就实现了使用okhttp的get方式请求网络。是不是很简单呢!赶紧去试试吧!
如发现错误,请指正,谢谢!!!共同交流,共同学习