工具介紹
使用:
- AndroidStudio:【compile 'com.squareup.okhttp3:okhttp:3.4.2'】和【compile 'com.zhy:okhttputils:2.6.2'】和【compile 'com.google.code.gson:gson:2.3.1'】
- eclipse:添加okthttp、okio、gson的jar包,復制okhttputils的源碼到項目中
![]()
![]()
![]()
封裝的功能
- 一般的get請求
- 一般的post請求
- 基於Http Post的文件上傳(類似表單)
- 文件下載/加載圖片
- 上傳下載的進度回調
- 支持取消某個請求
- 支持自定義Callback
- 支持HEAD、DELETE、PATCH、PUT
- 支持session的保持
- 支持自簽名網站https的訪問,提供方法設置下證書就行
<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />android:name="com.bqt.okhttp.MyApplication"
Application
public class MyApplication extends Application {@Overridepublic void onCreate() {super.onCreate();//對於Https,框架中提供了一個類HttpsUtils,可設置為:可訪問所有的https網站、設置具體的證書、雙向認證//同樣的,框架中只是提供了幾個實現類,你可以自行實現SSLSocketFactory,傳入sslSocketFactory方法中即可HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);//對於cookie,直接通過cookiejar方法配置,當然也可以自己實現CookieJar接口,編寫cookie管理相關代碼。//對於持久化cookie,還可以使用https://github.com/franmontiel/PersistentCookieJar.相當於框架中只是提供了幾個實現類,你可以自行定制或者選擇使用// ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getApplicationContext()));// CookieJarImpl cookieJar = new CookieJarImpl(new MemoryCookieStore());OkHttpClient okHttpClient = new OkHttpClient.Builder()//.connectTimeout(10000L, TimeUnit.MILLISECONDS)//.readTimeout(10000L, TimeUnit.MILLISECONDS)////對於Log,初始化OkhttpClient時,通過設置攔截器實現,框架中提供了一個LoggerInterceptor,當然你可以自行實現一個Interceptor.addInterceptor(new LoggerInterceptor("TAG"))//// .cookieJar(cookieJar).hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}})//.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)//.build();//默認情況下,將直接使用okhttp默認的配置生成OkhttpClient,如果有任何配置,記得在Application中調用initClient方法進行設置。OkHttpUtils.initClient(okHttpClient);}}
MainActivity
![]()
![]()
public class MainActivity extends ListActivity {private User mUser;private String user = "103468";private String pass = "103468";private String session_id;private String uid;private String mBaseUrl = "http://tapi.95xiu.com/";private TextView mTv;private ImageView mImageView;private ProgressBar mProgressBar;protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);String[] array = { "post方式提交鍵值對數據", "get方式提交鍵值對數據", "post方式提交鍵值對數據文件", "post方式提交文件",//"post方式提交Json數據", "get方式獲取圖片", "get方式下載文件", "清除Session", };for (int i = 0; i < array.length; i++) {array[i] = i + "、" + array[i];}mTv = new TextView(this);// 將內容顯示在TextView中mTv.setTextColor(Color.BLUE);mTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);mTv.setPadding(20, 10, 20, 10);mImageView = new ImageView(this);mProgressBar = new ProgressBar(this);mProgressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);mProgressBar.setMax(100);getListView().addFooterView(mProgressBar);getListView().addFooterView(mTv);getListView().addFooterView(mImageView);setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>(Arrays.asList(array))));}
@Overrideprotected void onListItemClick(ListView l, View v, int position, long id) {switch (position) {case 0:postWithParams(); //post方式提交鍵值對數據break;case 1:getWithParams(); //get方式提交鍵值對數據break;case 2:postParamsAndFile(); //post方式提交鍵值對數據,同時提交文件break;case 3:postFile();//post方式提交文件---------------------用不到break;case 4:postJson();//post方式提交Json數據break;case 5:getImage();//get方式獲取圖片break;case 6:downloadFile();//get方式下載文件break;case 7:clearSession();//清除Sessionbreak;}}
//post方式提交鍵值對數據public void postWithParams() {String url = mBaseUrl + "user/loginv2.php";OkHttpUtils.post().url(url).addParams("user", user).addParams("pass", pass).build().execute(new StringCallback() {@Overridepublic void onBefore(Request request, int id) {mTv.setText("onBefore...\n\n");}@Overridepublic void onAfter(int id) {mTv.append("onAfter...");}@Overridepublic void onError(Call call, Exception e, int id) {e.printStackTrace();mTv.append("onError:" + e.getMessage() + "\n\n");}@Overridepublic void onResponse(String response, int id) {mTv.append(response + "\n\n");Log.i("bqt", response);mUser = new Gson().fromJson(response, User.class);uid = mUser.getMsg().getId();session_id = mUser.getMsg().getSession_id();}});}//get方式提交鍵值對數據public void getWithParams() {String url = mBaseUrl + "app/news/index.php";OkHttpUtils.get().url(url).id(100).addParams("session_id", session_id).addParams("uid", uid).build().execute(new MyStringCallback());}//post方式提交鍵值對數據,同時提交文件public void postParamsAndFile() {String url = mBaseUrl + "myprofile/editinfo.php";File file = new File(Environment.getExternalStorageDirectory(), "bqt.jpg");if (!file.exists()) {Toast.makeText(MainActivity.this, "文件不存在,請修改文件路徑", Toast.LENGTH_SHORT).show();return;}Map<String, String> params = new HashMap<>();params.put("session_id", session_id);params.put("uid", uid);OkHttpUtils.post().addFile("image", "文件名", file).url(url).params(params).build().execute(new MyStringCallback());//可以提交多個文件}//post方式提交文件---------------------用不到public void postFile() {String url = "http://app.fulijr.com/api/v1.3.4/a61000b6a80a";File file = new File(Environment.getExternalStorageDirectory(), "bqt.jpg");if (!file.exists()) {Toast.makeText(MainActivity.this, "文件不存在,請修改文件路徑", Toast.LENGTH_SHORT).show();return;}OkHttpUtils.postFile().url(url).file(file).build().execute(new MyStringCallback());}//post方式提交Json數據public void postJson() {String url = mBaseUrl + "user/loginv2.php";OkHttpUtils.postString().url(url).mediaType(MediaType.parse("application/json; charset=utf-8")).content(new Gson().toJson(mUser)).build().execute(new MyStringCallback());}//get方式獲取圖片public void getImage() {String url = "http://d.hiphotos.baidu.com/image/pic/item/e4dde71190ef76c6cc15d5839816fdfaae516756.jpg";OkHttpUtils.get().url(url).tag(this).build().connTimeOut(20000).readTimeOut(20000).writeTimeOut(20000)//.execute(new BitmapCallback() {@Overridepublic void onError(Call call, Exception e, int id) {mTv.setText("onError:" + e.getMessage());}@Overridepublic void onResponse(Bitmap bitmap, int id) {mImageView.setImageBitmap(bitmap);}});}//get方式下載文件public void downloadFile() {String url = "http://d.hiphotos.baidu.com/image/pic/item/e4dde71190ef76c6cc15d5839816fdfaae516756.jpg";String filePath = Environment.getExternalStorageDirectory().getAbsolutePath();OkHttpUtils.get().url(url).build().execute(new FileCallBack(filePath, "包青天.jpg") {@Overridepublic void onBefore(Request request, int id) {mTv.setText("onBefore...\n\n");}@Overridepublic void onAfter(int id) {mTv.append("onAfter...");}@Overridepublic void inProgress(float progress, long total, int id) {mProgressBar.setProgress((int) (100 * progress));mTv.append(progress + "\n");}@Overridepublic void onError(Call call, Exception e, int id) {e.printStackTrace();mTv.append("onError:" + e.getMessage() + "\n\n");}@Overridepublic void onResponse(File file, int id) {mTv.append(file.getAbsolutePath() + "\n\n");}});}//清除Sessionpublic void clearSession() {CookieJar cookieJar = OkHttpUtils.getInstance().getOkHttpClient().cookieJar();if (cookieJar instanceof CookieJarImpl) {((CookieJarImpl) cookieJar).getCookieStore().removeAll();}}//其他請求方式public void otherRequestDemo() {//also can use delete ,head , patchOkHttpUtils.put().url("http://11111.com").requestBody("may be something").build()//.execute(new MyStringCallback());try {OkHttpUtils.head().url("http://11111.com").addParams("name", "zhy").build().execute();} catch (IOException e) {e.printStackTrace();}}@Overrideprotected void onDestroy() {super.onDestroy();OkHttpUtils.getInstance().cancelTag(this);}public class MyStringCallback extends StringCallback {@Overridepublic void onError(Call call, Exception e, int id) {e.printStackTrace();mTv.setText("onError:" + e.getMessage());}@Overridepublic void onResponse(String response, int id) {mTv.setText("onResponse:" + decodeUnicodeToString(response));}}/**將Unicode編碼解析成字符串形式(如漢字) */public static String decodeUnicodeToString(String uString) {StringBuilder sb = new StringBuilder();int i = -1, pos = 0;while ((i = uString.indexOf("\\u", pos)) != -1) {sb.append(uString.substring(pos, i));if (i + 5 < uString.length()) {pos = i + 6;sb.append((char) Integer.parseInt(uString.substring(i + 2, i + 6), 16));}}sb.append(uString.substring(pos));return sb.toString();}}
附件列表