okhttp 是一个 Java 的 HTTP+SPDY 客户端开发包,同时也支持 Android。需要Android 2.3以上。
返回执行结果
private String get(String url) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); Response response = null; try { response = client.newCall(request).execute(); return response.body().string(); } catch (IOException e) { e.printStackTrace(); } return null; }
POST需要使用RequestBody对象,之后再构建Request对象时调用post函数将其传入即可
private String post(String url) { OkHttpClient client = new OkHttpClient(); RequestBody formBody = new FormEncodingBuilder() .add("user", "Jurassic Park") .add("pass", "asasa") .add("time", "12132") .build(); Request request = new Request.Builder() .url(url) .post(formBody) .build(); Response response = null; try { response = client.newCall(request).execute(); return response.body().string(); } catch (IOException e) { e.printStackTrace(); } return null; }
此外,post的使用方法还支持文件等操作,具体使用方法有兴趣的可以自行查阅
okHttp还自带了对Gson的支持
private Person gson(String url){ OkHttpClient client = new OkHttpClient(); Gson gson = new Gson(); Request request = new Request.Builder() .url(url) .build(); Response response = null; try { response = client.newCall(request).execute(); Person person = gson.fromJson(response.body().charStream(), Person.class); return person; } catch (IOException e) { e.printStackTrace(); } return null; }
以上的两个例子必须在子线程中完成,同时okHttp还提供了异步的方法调用,通过使用回调来进行异步调用,然后okHttp的回调依然不在主线程中,因此该回调中不能操作UI
private void getAsync(String url) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); Response response = null; client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { String result = response.body().string(); Toast.makeText(getApplicationContext(),result,Toast.LENGTH_SHORT).show(); //不能操作ui,回调依然在子线程 Log.d("TAG", result); } }); }
项目主页:http://www.open-open.com/lib/view/home/1435381866122