这里是我的代码
TwitterRestClient
import android.content.Context;
import com.loopj.android.http.*;
import cz.msebera.android.httpclient.entity.StringEntity;
public class TwitterRestClient {
private static final String BASE_URL = "https://www.example.com/api/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(Context ctx, String url, StringEntity entity, java.lang.String contentType, AsyncHttpResponseHandler responseHandler){
client.post(ctx,getAbsoluteUrl(url),entity,contentType,responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
此方法在我LoginAcitivity
public void testPost(StringEntity entity) throws JSONException {
TwitterRestClient.post(getApplicationContext(),"api-auth/", entity,"application/json", new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, org.json.JSONArray response) {
// If the response is JSONObject instead of expected JSONArray
GlobalFunctions.ShowToast(getApplicationContext(),"test");
}
@Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, java.lang.Throwable throwable, org.json.JSONArray errorResponse){
GlobalFunctions.ShowToast(getApplicationContext(),"test1123");
}
@Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, java.lang.Throwable throwable, org.json.JSONObject errorResponse){
GlobalFunctions.ShowToast(getApplicationContext(),errorResponse.toString());
}
@Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, java.lang.String responseString, java.lang.Throwable throwable){
GlobalFunctions.ShowToast(getApplicationContext(),responseString);
}
});
}
这就是我所说的,当用户点击这个按钮
public void signIn(View v){
try {
String url = "/api-auth";
JSONObject jsonParams = new JSONObject();
jsonParams.put("username", "[email protected]");
jsonParams.put("password", "cornedbeef");
StringEntity entity = new StringEntity(jsonParams.toString());
client.post(context, url, entity, "application/json",
responseHandler);
testPost(entity);
} catch (Exception err)
{
GlobalFunctions.ShowToast(this, err.toString());
}
}
希望这会帮助你,告诉我这是不是工作,因为我在发布之前编辑这个。
有趣的是代码的作品? onSuccess和onFailure都会在适当的时候被调用,但是我仍然会在代码下面看到红色的错误行。 onSuccess和onFailure的错误是“方法不会覆盖超类的方法,(状态码....)的错误是”无法解析方法onsuccess ...“。我会继续挖掘如何使错误消失 – timv
我现在有这个问题,你有能力解决这个问题吗? – Binsoi
仍然在工作,所以检查回来,我会得到答案一些如何 – timv