我正在使用OKHttp对服务器执行Post请求,如下所示:
public class NetworkManager { public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); String post(String url, JSONObject json) throws IOException { try { JSONArray array = json.getJSONArray("d"); RequestBody body = new FormEncodingBuilder() .add("m", json.getString("m")) .add("d", array.toString()) .build(); Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = client.newCall(request).execute(); return response.body().string(); } catch (JSONException jsone) { return "ERROR: " + jsone.getMessage(); } } }
并称之为:
NetworkManager manager = new NetworkManager(); String response = manager.post("http://www.example.com/api/", jsonObject);
当我尝试运行App时,它会在logcat中提示错误:
android.os.StrictMode
$ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)中的android.os.NetworkOnMainThreadException
参考SO中的其他问题,我添加了这个以覆盖策略:
if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); }
但我认为这是不健康的,我想把这些NetworkManager
行动置于背景之下.我怎么能这样做?
由于OkHttp也支持异步方式,因此IMO可以参考以下GET请求示例,然后申请POST请求:
OkHttpClient client = new OkHttpClient(); // GET request Request request = new Request.Builder() .url("http://google.com") .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { Log.e(LOG_TAG, e.toString()); } @Override public void onResponse(Response response) throws IOException { Log.w(LOG_TAG, response.body().string()); Log.i(LOG_TAG, response.toString()); } });
希望能帮助到你!