【发布时间】:2015-04-28 12:01:36
【问题描述】:
我正在使用 OkHttp 并且一切正常,但是,我想考虑以下情况:DNS 解析关闭、服务器关闭、速度缓慢或仅返回 HTTP 状态代码 200 以外的内容。 我试过使用 Toast,但我不能,因为这是在另一个线程上完成的(?)。 如何克服这个障碍,给用户更好的体验? 这是我的代码:
private void getBinary(String text) throws Exception {
OkHttpClient client = new OkHttpClient();
String body = URLEncoder.encode(text, "utf-8");
// Encrypt
MCrypt mcrypt = new MCrypt();
String encrypted = MCrypt.bytesToHex(mcrypt.encrypt(body));
Request request = new Request.Builder()
.url("http://mysite/my_api.php")
.post(RequestBody.create(MediaType.parse("text/plain"), encrypted))
.addHeader("User-Agent", System.getProperty("http.agent"))
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Response response) throws IOException, RuntimeException {
if (response.code() != 200){
Toast.makeText(getSherlockActivity(), "Fail", Toast.LENGTH_LONG).show();
return;
}
saveResponseToFile(response);
}
@Override
public void onFailure(Request arg0, IOException arg1) {
Toast.makeText(getSherlockActivity(), "Bigger fail", Toast.LENGTH_LONG).show();
}
});
}
这是崩溃:
FATAL EXCEPTION: OkHttp Dispatcher
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
【问题讨论】:
-
确保不从主 Ui 线程调用
getBinary方法?
标签: android okhttp android-toast