Hello I'm trying to receive some data from this API
http://docs.sygictravelapi.com/1.1/
The problem is that I'm getting on failure all the time with these exceptions:
Failure cz.msebera.android.httpclient.client.HttpResponseException:
Unauthorized Status Code: 401
I think the problem is that I don't send a Header!
My code is:
RequestParams params = new RequestParams();
params.put("location", locationParameter);
params.put("x-api-key", API_KEY);
AsyncHttpClient client = new AsyncHttpClient();
client.get(API_URL, params, new JsonHttpResponseHandler(){
#Override
public void onSuccess(int status, Header[] headers, JSONObject response)
{
Log.d("App", "JSON: " + response.toString());
}
#Override
public void onFailure(int status, Header[] headers, Throwable ex, JSONObject response)
{
Log.e("Dimos", "Failure " + ex.toString());
Log.d("Dimos", "Status Code: " + status);
Toast.makeText(MainActivityController.this, "Failure", Toast.LENGTH_SHORT).show();
}
});
Related
I'm using android-async-http for rest request. When I doing post request then the response body is empty. When I use postman for the same request I received a response as JSONObject.
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth(getResources().getString(R.string.api_user), getResources().getString(R.string.api_password));
String requestAddress = getResources().getString(R.string.api_base_address) + getResources().getString(R.string.api_event_address);
JSONObject params = new JSONObject();
params.put("name", mEditTextName.getText().toString());
params.put("place", mEditTextPlace.getText().toString());
params.put("dateAndTime", DateUtils.sdfWithFullTime.format(DateUtils.sdfWithTime.parse(mEditTextDate.getText().toString())));
Log.d(TAG, "onClick: " + params.toString());
StringEntity stringParams = new StringEntity(params.toString());
client.post(getApplicationContext(), requestAddress, stringParams, "application/json", new TextHttpResponseHandler() {
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.e(TAG, "onFailure: error during creating event " + responseString,throwable );
Toast.makeText(getBaseContext(),"Error during creating event",Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
Toast.makeText(getBaseContext(),"Successfully create event",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getBaseContext(), EventListActivity.class);
startActivity(intent);
}
});
} catch (Exception e) {
Log.e(TAG, "createEvent: error during creating event", e);
}
}
Check parameters and base url, use volley or retrofit library to Post request.
I have a issue and I need a help. I want to get updates from server via long polling. I'm using this library for server communication. https://github.com/loopj/android-async-http. Here is a code what I'm using
private void connectService() {
AsyncHttpClient httpClient = new AsyncHttpClient();
httpClient.setBasicAuth("key", "");
BaseJsonHttpResponseHandler handler = new BaseJsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Object response) {
Log.e(TAG, "success body " + rawJsonResponse);
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, Object errorResponse) {
Log.e(TAG, "error " + throwable.toString());
}
#Override
protected Object parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
Log.e(TAG, "response body " + rawJsonData);
return null;
}
#Override
public void onPreProcessResponse(ResponseHandlerInterface instance, HttpResponse response) {
super.onPreProcessResponse(instance, response);
Log.e(TAG, "pre progress " + instance.getRequestURI());
}
};
httpClient.get(this, url, null, handler);
}
So I tested in browser and everything is work, but I didn't get any response on my device and also which library you is the best for using long polling?
Thanks
i am new to AndroidAsyncHttp.
i created a class httptester :
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);
}
private static String getAbsoluteUrl(String relativeUrl) {
return relativeUrl;
}
and in my activity did the following:
RequestParams params = new RequestParams();
params.put("FTID", HTTPRequestUserAuthentication.AppID);
params.put("UUID", MainActivity.uuid);
params.put("TYPE", "11");
params.put("DateTimeStamp", DateTimeStamp);
params.put("SDFVersionNb", SDFVersionNb);
httptester.post(MainActivitySharedPref.GetValue(MyApplication.getContext(), "WebService_URL")+MyApplication.getContext().getResources().getString(R.string.url_get_user_data), params,new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
super.onSuccess(statusCode, headers, responseString);
Log.e(TAG, "sucess: " + responseString);
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.e(TAG, "failure: " + responseString);
Log.e(TAG, "failurecode: " + statusCode);
super.onFailure(statusCode, headers, responseString, throwable);
}
});
after calling the client, the correct response is being returned but it is being returned in OnFailure and not in OnSuccess. i also printed the status code in onfailure and it is 200 which supposedly should be OK.
any help would be appreciated.
So you call in your request
new JsonHttpResponseHandler()
But you need
new AsyncHttpResponseHandler()
I am using the LoopJ AndroidAsyncHttp Library in an Android Project but when I try to get the parameters at the server side, I get null. I tried using PHP & Java same result. I am 100% sure my server side is working since I use postman chrome plugin and it works:
Client Code:
public void sendRequest(View v) {
try {
AsyncHttpClient client = new AsyncHttpClient();
// HashMap<String, String> paramsMap = new HashMap<String,
// String>();
// paramsMap.put("action", "Action Value");
// RequestParams params = new RequestParams(paramsMap);
RequestParams params = new RequestParams();
params.add("action", "insert");
AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers,
byte[] body) {
System.out.println("On Success --> Status Code: "
+ statusCode);
String response = new String(body);
System.out.println("On Success --> Response: " + response);
}
#Override
public void onFailure(int statusCode, Header[] headers,
byte[] body, Throwable error) {
System.out.println("On Failure --> Status Code: "
+ statusCode);
}
};
String url1 = "http://192.168.1.9:8080/Tester";
String url2 = "http://192.168.1.6/test";
System.out.println("--->>> Params: " + params.toString());
client.post(url1, params, handler);
} catch (Exception e) {
System.out.println("--> Exception: " + e.getMessage());
}
}
Server Code (Java):
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("------->>> " + request.getParameter("action"));
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet FrontEndController</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet FrontEndController at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
I am trying to upload files from an Android application to Mediafire using their upload API resource. Also, I am using Android Asynchronous Http Client through out the app to handle the REST calls.
Problem:
The upload fails because of Mediafire returns code -99, "-99 : Missing or invalid session token".
I'm passing session_token along with 3 other parameters including the image file.
Here is the POST call:
RequestParams upload_params = new RequestParams();
File myFile = new File(image.getPath());
try {
upload_params.put("filename", myFile);
} catch(FileNotFoundException e) {
}
upload_params.put("session_token", session_token);
upload_params.put("uploadkey", MyConstants.MEDIA_FOLDER_KEY);
upload_params.put("response_format", MyConstants.MEDIA_RESPONSE_FORMAT);
Log.d("PARAMS: ", upload_params.toString());
client.post(MyConstants.MEDIA_BASE_URL + MyConstants.MEDIA_UPLOAD, upload_params, new JsonHttpResponseHandler() {
#Override
public void onStart() {
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
String response_string = new String(response);
Log.d("RESPONSE: ", response_string);
Log.d("SESSION_TOKEN: ", session_token);
Log.d("STATUS CODE: ", Integer.toString(statusCode));
for(int i = 0; i < headers.length; i++) {
Log.d("Header " + i + ": ", headers[i].toString());
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
}
});
I don't know why but I think my session_token, uploadkey and response_format are not being sent because when I look at the logcat I see the response I get back from Mediafire is in XML.
Any help will be greatly appreciated! Let me know if more information is needed.
So after countless hours of debugging (3 days worth) that lead no where I finally figured out why the upload wouldn't go through.
Basically Mediafire requires only the file as the POST parameter. It expects the session_token, uploadkey and other parameters as GET.
I changed my upload_params and POST request to the following to get it working:
RequestParams upload_params = new RequestParams();
File myFile = new File(image.getPath());
try {
upload_params.put("filename", myFile);
} catch(FileNotFoundException e) {
}
client.post(MyConstants.MEDIA_BASE_URL + MyConstants.MEDIA_UPLOAD +
"?session_token=my_session_token" +
"&uploadkey=" + MyConstants.MEDIA_FOLDER_KEY +
"&response_format=" + MyConstants.MEDIA_RESPONSE_FORMAT),
upload_params,
new JsonHttpResponseHandler() {
#Override
public void onStart() {
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
Log.d("RESPONSE: ", new String(response));
Log.d("SESSION_TOKEN: ", session_token);
Log.d("STATUS CODE: ", Integer.toString(statusCode));
for(int i = 0; i < headers.length; i++) {
Log.d("Header " + i + ": ", headers[i].toString());
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
}
});