android studio中OkHttp请求数据

时间:2022-11-12 20:53:28
 1:首先在GitHub中找到OkHttp 在找到下面那行代码,把下面的那句代码粘贴到build.grable里面 android studio中OkHttp请求数据

2:在输入这个网站找到OkHttp的网址 ,点击Examples有例子
android studio中OkHttp请求数据


3:然后直接按着上面的例子,一步步完成,我直接上我的写的一个小案例了,可以改改直接用

package com.example.okhttpdemo;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;
import java.io.IOException;
import butterknife.ButterKnife;
import butterknife.InjectView;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MainActivity extends Activity {

Handler mHandler=new Handler();
@InjectView(R.id.iv)
ImageView iv;
// 图片的网址
private final String path = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png";


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
initData(path);



}

private void initData(final String path) {

new Thread(new Runnable() {
@Override
public void run() {


// 创建okHttpClient
OkHttpClient client = new OkHttpClient();
// 创建一个请求
Request request = new Request.Builder()
.url(path)
.build();
//给okhttpClient传入一个请求,这个时候得到一个call
Call call = client.newCall(request);
try {
Response response = call.execute();
int code = response.code();
if (code == 200) {
ResponseBody body = response.body();
byte[] bytes = body.bytes();
final Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
mHandler.post(new Runnable() {
@Override
public void run() {
iv.setImageBitmap(bitmap);
}
});

}
} catch (IOException e) {
e.printStackTrace();
}


}
}).start();
}
}
4:在xml文件定义一个ImageView控件

<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>