使用步骤:
1.添加依赖:
compile 'com.squareup.okhttp3:okhttp:3.4.1' compile 'com.squareup.okio:okio:1.11.0'
2.xml布局文件
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:text="okhttp异步下载图片" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentStart="true" android:id="@+id/asyncBtn" /> <Button android:text="okhttp同步下载图片" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentStart="true" android:id="@+id/synchronizedBtn" /> </LinearLayout> <ImageView android:id="@+id/imageview" android:layout_width="match_parent" android:layout_height="200dp" />
3.activity
public class FirstFragment extends Fragment { Button asyncBtn, synchronizedBtn; ImageView imageView; private final String IMAGE_URL = "http://ww4.sinaimg.cn/large/006uZZy8jw1faic21363tj30ci08ct96.jpg"; private static final int IS_SUCCESS = 1; private static final int IS_FAIL = 0; private OkHttpClient client; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case IS_SUCCESS: //成功显示图片 byte[] bytes = (byte[]) msg.obj; Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); imageView.setImageBitmap(bitmap); break; case IS_FAIL: //失败显示图片 Toast.makeText(getActivity(), "对不起,下载失败", Toast.LENGTH_SHORT).show(); break; default: break; } } }; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.first_fragment, container, false); asyncBtn = (Button) view.findViewById(R.id.asyncBtn); synchronizedBtn = (Button) view.findViewById(R.id.synchronizedBtn); imageView = (ImageView) view.findViewById(R.id.imageview); asyncBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new Thread(new Runnable() { @Override public void run() { synchronizedGet(); } }).start(); } }); synchronizedBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { asyncGet(); } }); return view; } /** * 异步get,直接调用 */ private void asyncGet() { client = new OkHttpClient(); final Request request = new Request.Builder().get() .url(IMAGE_URL) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { Message message = handler.obtainMessage(); if (response.isSuccessful()) { message.what = IS_SUCCESS; message.obj = response.body().bytes(); handler.sendMessage(message); } else { handler.sendEmptyMessage(IS_FAIL); } } }); } /** * 同步写法,需要放在子线程中使用 */ private void synchronizedGet() { client = new OkHttpClient(); final Request request = new Request.Builder().get() .url(IMAGE_URL) .build(); try { Response response = client.newCall(request).execute(); Message message = handler.obtainMessage(); if (response.isSuccessful()) { message.what = IS_SUCCESS; message.obj = response.body().bytes(); handler.sendMessage(message); } else { handler.sendEmptyMessage(IS_FAIL); } } catch (IOException e) { e.printStackTrace(); } } /** * 使用FormBody传递键值对参数 */ private void postDataWithParame() { OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。 FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体 formBody.add("username","zhangsan");//传递键值对参数 Request request = new Request.Builder()//创建Request 对象。 .url("http://www.baidu.com") .post(formBody.build())//传递请求体 .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 { } });//此处省略回调方法。 } /** * 使用RequestBody传递Json或File对象RequestBody是抽象类,故不能直接使用,但是他有静态方法create, * 使用这个方法可以得到RequestBody对象。 */ private void postDataJsonParame(){ OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。 MediaType JSON = MediaType.parse("application/json; charset=utf-8");//数据类型为json格式, String jsonStr = "{\"username\":\"lisi\",\"nickname\":\"李四\"}";//json数据. RequestBody body = RequestBody.create(JSON, jsonStr); Request request = new Request.Builder() .url("http://www.baidu.com") .post(body) .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 { } });//此处省略回调方法。 } /** * 上传File对象使用 */ private void postDataFileParame(){ OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。 MediaType fileType = MediaType.parse("File/*");//数据类型为json格式, File file = new File("path");//file对象. RequestBody body = RequestBody.create(fileType , file ); Request request = new Request.Builder() .url("http://www.baidu.com") .post(body) .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 { } });//此处省略回调方法。 } /** * 使用MultipartBody同时传递键值对参数和File对象 */ private void multipartBodyDataParame(){ String fileName = ""; File file = new File(fileName); OkHttpClient client = new OkHttpClient(); MultipartBody multipartBody =new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("groupId","")//添加键值对参数 .addFormDataPart("title","title") .addFormDataPart("file",file.getName(),RequestBody.create(MediaType.parse("file/*"), file))//添加文件 .build(); final Request request = new Request.Builder() .url("") .post(multipartBody) .build(); } /** * 文件下载 * 在OKHttp中并没有提供下载文件的功能,但是在Response中可以获取流对象,有了流对象我们就可以自己实现文件的下载 */ private void getDataFileShow(){ client = new OkHttpClient(); final Request request = new Request.Builder().get() .url(IMAGE_URL) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { try{ InputStream is = response.body().byteStream();//从服务器得到输入流对象 long sum = 0; File dir = new File(""); if (!dir.exists()){ dir.mkdirs(); } File file = new File(dir, "");//根据目录和文件名得到file对象 FileOutputStream fos = new FileOutputStream(file); byte[] buf = new byte[1024*8]; int len = 0; while ((len = is.read(buf)) != -1){ fos.write(buf, 0, len); } fos.flush(); }catch (EOFException e){ } } }); }