我正在使用android-async-http 1.4.5
,但我发现它从不调用我的服务器,这是我的代码:
public class HttpUtils {
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
params.setUseJsonStreamer(true);
client.get(url, params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
params.setUseJsonStreamer(true);
Log.i("URL", url);
client.post(url, params, responseHandler);
}
}
以下是我定义处理程序的方法:
public abstract class JsonResponseHandler extends AsyncHttpResponseHandler {
private static final String TAG = "JSON_RESPONSE_HANDLER";
public abstract void onSuccess(int statusCode, Header[] headers, JSONObject jsonObject);
public abstract void onFailure(int statusCode, Header[] headers, JSONObject jsonObject);
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.i(TAG, "on success");
onSuccess(statusCode, headers, parseObject(responseBody));
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.i(TAG, "on failure");
onFailure(statusCode, headers, parseObject(responseBody));
}
private JSONObject parseObject(byte[] response) {
JSONObject jsonObj = null;
try {
String json = new String(response, "UTF-8");
jsonObj = new JSONObject(json);
} catch (Exception e) {
e.printStackTrace();
}
return jsonObj;
}
}
经过一些调试工作后,我发现我的代码实际执行client.post(...)
,但我的服务器没有收到任何调用。
以下是我在测试用例中使用它的方法:
public class VerifyCodeTest extends TestCase {
private static final String TAG ="VERIFY_CODE_TEST";
public void testGetVerifyCode(){
Log.i(TAG, "Hello World");
VerifyCodeTransaction vc= new VerifyCodeTransaction("167xxxx137");
vc.execute(new JsonResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject jsonObject) {
Log.i(TAG, "SUCCESS");
Log.i(TAG, jsonObject.toString());
}
@Override
public void onFailure(int statusCode, Header[] headers, JSONObject jsonObject) {
Log.i(TAG, "FAILURE");
Log.i(TAG, jsonObject.toString());
}
});
}
}
答案 0 :(得分:0)
我不知道您是仅在TestCase中还是在App中遇到此问题。我认为图书馆在单元测试中效果不佳!!来源:https://github.com/loopj/android-async-http/issues/321
我过去在库中遇到过类似的问题,我通过从github repo中的源代码编译库来解决它
使用最新版本的库可能会更好:)