一首先下載Jar包 https://github.com/square/okhttp 如果使用android studio只需要加入依賴 二--下載一張圖片並顯示 使用的是hanlder的方式 也可以把網路請求寫為一個工具類, get方式 ...
一首先下載Jar包
https://github.com/square/okhttp
如果使用android studio只需要加入依賴
compile 'com.squareup.okhttp3:okhttp:3.2.0'
二--下載一張圖片並顯示
使用的是hanlder的方式
package com.liunan.okhttpdemo2; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import java.io.IOException; import java.io.InputStream; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; public class MainActivity extends AppCompatActivity { private static final int ERROR = 1; private static final int SUCCESS = 2 ; private String url = "http://192.168.1.102:8080/img/a.jpg"; private ImageView mIv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case SUCCESS: mIv.setImageBitmap((Bitmap) msg.obj); break; case ERROR: Toast.makeText(MainActivity.this, "請求超時", Toast.LENGTH_SHORT).show(); break; } } }; /** * 初始化 組件 */ private void initView() { mIv = (ImageView) findViewById(R.id.main_iv); } /** * 點擊獲取圖片 */ public void getPic(View v){ new Thread(){ @Override public void run() { //獲取okHttp對象get請求, try { OkHttpClient client = new OkHttpClient(); //獲取請求對象 Request request = new Request.Builder().url(url).build(); //獲取響應體 ResponseBody body = client.newCall(request).execute().body(); //獲取流 InputStream in = body.byteStream(); //轉化為bitmap Bitmap bitmap = BitmapFactory.decodeStream(in); //使用Hanlder發送消息 Message msg = Message.obtain(); msg.what = SUCCESS; msg.obj = bitmap; handler.sendMessage(msg); } catch (IOException e) { e.printStackTrace(); //失敗 Message msg = Message.obtain(); msg.what = ERROR; handler.sendMessage(msg); } } }.start(); } }
也可以把網路請求寫為一個工具類,
package com.liunan.okhttpdemo2; import java.io.IOException; import java.io.InputStream; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * Created by 劉楠 on 2016-03-27. */ public class OkHttpUtils { OkHttpClient client = new OkHttpClient(); /** * 獲取流 * @param url 請求地址 * @return 輸入流 */ public InputStream getInpuStream(String url) throws IOException { //設置 請求 Request request = new Request.Builder() .url(url).build(); //獲取行響應 InputStream in = client.newCall(request).execute().body().byteStream(); return in; } /** * 返回字元串 * @param url * @return 返回字元串 * @throws IOException */ public String getString(String url) throws IOException { //設置 請求 Request request = new Request.Builder() .url(url).build(); //獲取行響應 Response response = client.newCall(request).execute(); return response.body().string(); } }
get方式