以前用的是原生的httpClient,但是有很多问题,比如重连机制啊,超时处理,等等,都需要自己写,而自己写又写不那么完善。
square开源的OkHttp很多人都在用,我试了下确实很不错,以后就打算用这个。
官网:http://square.github.io/okhttp/
注意,需要它需要okio包支持:https://github.com/square/okio
官方帮助文档:https://github.com/square/okhttp/wiki/Recipes
这里就简单的记录下它的Post用法:
第一种是需要在线程里运行的:
public String postKeyValue(String actionType, String jsonString, String url) throws HttpException, IOException { String result = null; FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder(); addCommonData(formEncodingBuilder); formEncodingBuilder.add("actionType", actionType); formEncodingBuilder.add(Value.JSON_STR, jsonString); RequestBody formBody = formEncodingBuilder.build(); Request request = new Request.Builder() .url(url) .post(formBody) .build(); Response response = okHttpClient.newCall(request).execute(); if (response.isSuccessful()){ result = response.body().string(); }else { throw new IOException("Unexpected code " + response); } return result; }
public void postKeyValue(String actionType, String jsonString, String url) throws HttpException, IOException { FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder(); addCommonData(formEncodingBuilder); formEncodingBuilder.add("actionType", actionType); formEncodingBuilder.add(Value.JSON_STR, jsonString); RequestBody formBody = formEncodingBuilder.build(); Request request = new Request.Builder() .url(url) .post(formBody) .build(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(final Response response) throws IOException { if (response.isSuccessful()) { String result = response.body().string(); } else { throw new IOException("Unexpected code " + response); } } }); }