LoopJ AndroidAsyncHttp PUT, how to do? - android

I need some help correcting my approach for using the following API > https://github.com/Privo/PRIVO-Hub/wiki/Web-Services-API-Reference#update-user-display-name.
I am unsure of how to send a JSON object for update using LoopJ AndroidAsyncHttp PUT. I am receiving the following error response
{"message":"Error: null","validationErrors":[]."responseTimestamp":141936124612,"totalCount":-1,"status":"failed","resultCount":-1,"entity":null}
How am I doing this wrong?
AsyncHttpClient client = null;
String authorizationHeader = "token_type", "" + " " + "access_token", "");
client.addHeader("Authorization", authorizationHeader);
client.addHeader("Content-type", "application/json");
client.addHeader("Accept", "application/json");
String requestBody = "displayName=" + "hardcodedDisplayName";
String requestURL = "https://privohub.privo.com/api/" + "account/public/saveDisplayName?" + requestBody;
client.put(requestURL, new ResponseHandler(myClass.this, "displayName", new OnResponseHandler() {
#Override
public void onSuccess(int statusCode, String apiName, JSONObject response) {
if (statusCode == 200) {
Log.i(TAG, "Seems to be working")
}
}
#Override
public void onFailure(int statusCode, String apiName, String responseMessage) {
Log.i(TAG, "Fail: " + responseMessage);
}
#Override
public void onFailure(int statusCode, String apiName, JASONArray errorResponse) {
Log.i(TAG, "Fail: " + errorResponse);
}
#Override
public void onFailure(int statusCode, String apiName, JSONObject errorResponse) {
if (errorResponse != null) {
Log.i(TAG, "Fail: " + errorResponse);
}
}
}));

Looks like you are using AsyncHttpClient,
Use the preparePut and AsyncHttpClient.BoundRequestBuilder builder as in the examples/readme,
AsyncHttpClient client = new AsyncHttpClient(); // not null
// other code here
String requestBody = "displayName=" + "hardcodedDisplayName";
String requestURL = "https://privohub.privo.com/api/" + "account/public/saveDisplayName?" + requestBody;
client.preparePut(requestURL) // sets the urls the put request and gets a AsyncHttpClient.BoundRequestBuilder
.setBody(requestBody) // sets the body of the put request
.execute(new AsyncCompletionHandler<Response>(){
#Override
public Response onCompleted(Response response) throws Exception{
// Do something with the Response
// ...
return response;
}
#Override
public void onThrowable(Throwable t){
// Something wrong happened.
}
});

Related

Post request returns empty response body Android?

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.

Long polling issue: No response received

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

Send JSON as a POST request to server by AsyncHttpClient

I want to send JSON as a POST to my localhost server with LoopJ's AsndroidAsyncHttpt. I'm using this method:
public void post(Context context, String url, HttpEntity entity, String contentType, AsyncHttpResponseHandler responseHandler)
in my code but it doesn't work. Here is my code:
private void loginUser() throws JSONException, UnsupportedEncodingException {
String login = textLogin.getText().toString();
String password = textPassword.getText().toString();
JSONObject jsonObject = new JSONObject();
if(Utility.isNotNull(login) && Utility.isNotNull(password)) {
jsonObject.put("username", login);
jsonObject.put("password", password);
invokeWS(jsonObject);
}
else{
Toast.makeText(getApplicationContext(), "Proszę wypełnić wszystkie pola!", Toast.LENGTH_LONG).show();
}
}
private void invokeWS(JSONObject jsonObject) throws UnsupportedEncodingException {
StringEntity entity = new StringEntity(jsonObject.toString());
AsyncHttpClient client = new AsyncHttpClient();
Log.i("SER", "http://" + Constants.address + ":" + Constants.port + "/silownia_java/rest/login/auth" + entity);
Log.i("SER", "http://" + Constants.address + ":" + Constants.port + "/silownia_java/rest/login/auth" + jsonObject);
client.post(getApplicationContext(), "http://" + Constants.address + ":" + Constants.port + "/silownia_java/rest/login/auth", entity, "application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject obj) {
try {
Log.i("SER", "HERE!");
String login = obj.getString("login");
int ID = obj.getInt("id");
//user.setUserId(obj.getInt("userid"));
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "404 - Nie odnaleziono serwera!", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "500 - Coś poszło nie tak po stronie serwera!", Toast.LENGTH_LONG).show();
} else if (statusCode == 403) {
Toast.makeText(getApplicationContext(), "Podano niepoprawne dane!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), throwable.toString(), Toast.LENGTH_LONG).show();
}
}
});
}
My Logs looks ok:
http://MY_IP_ADDRESS:8080/silownia_java/rest/login/authorg.apache.http.entity.StringEntity#384d6a6d
http://MY_IP_ADDRESS:8080/silownia_java/rest/login/auth{"username":"barni","password":"12345"}
But i get such error:
org.apache.http.client.HttpResponseException: Unsupported Media Type
Additionaly, I know that server doesn't get any request. So, what the cause could be?
I solved it, by adding header information to my entity object.
ByteArrayEntity entity = new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

LoopJ AndroidAsyncHttp Library: Server Recieves Null Parameters

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>");
}
}

Posting image files to mediafire's upload resource using Android Asynchronous Http Client

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) {
}
});

Categories

Resources