這裏是我的代碼
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