Send JSON as a POST request to server by AsyncHttpClient - android

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

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.

AndroidHttpAsync not working at oncreate method

Whenever I use AsyncHttpClient in onCreate(Bundle savedInstanceState), onSuccess() method never used.
I put a break point, than debug... Never visit to break point if the break point is in the onSuccess() method, but when I put a button, after button click, it works?
I need to get values in onCreate() methods...
String url = "http://192.168.56.1:8080/restfulwssample/rest/examples/wsetkinlikgetir/";
url = url + eposta;
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
client.get(url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
try {
arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonobject = arr.getJSONObject(i);
String ali = jsonobject.getString("etkinlikAdi");
etkinlikAdlari[i] = jsonobject.getString("etkinlikTarihi");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Throwable error,
String content) {
// When Http response code is '404'
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "404", Toast.LENGTH_LONG);
}
// When Http response code is '500'
else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "500", Toast.LENGTH_LONG);
}
// When Http response code other than 404, 500
else {
Toast.makeText(getApplicationContext(), "Else", Toast.LENGTH_LONG);
}
}
});
Of course, i can share my activity code
public class TestActivity extends Activity{
JSONArray arr = null;
String[] etkinlikAdlari;
String eposta;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_count_down_temp);
String url = "http://192.168.56.1:8080/restfulwssample/rest/examples/wsetkinlikgetir/";
url = url + eposta;
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
client.get(url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
try {
arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonobject = arr.getJSONObject(i);
String ali = jsonobject.getString("etkinlikAdi");
etkinlikAdlari[i] = jsonobject.getString("etkinlikTarihi");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Throwable error,
String content) {
// When Http response code is '404'
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "404", Toast.LENGTH_LONG);
}
// When Http response code is '500'
else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "500", Toast.LENGTH_LONG);
}
// When Http response code other than 404, 500
else {
Toast.makeText(getApplicationContext(), "Else", Toast.LENGTH_LONG);
}
}
});
}
}

eror when parsing json android no data when run

This is my code how i use to load data with json..
client.get(URL, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject obj) {
try {
if (!obj.getBoolean("error")) {
JSONArray cest = obj.getJSONArray("list");
String z = "";
if (cest != null) {
int array = cest.length();
mDetail = new ArrayList<OrderItem>();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dateOrder = new Date();
for (int i = 0; i < array; i++) {
try {
dateOrder = formatter.parse(cest.getJSONObject(i).getString("OrderDate"));
} catch (ParseException e) {}
mDetail.add(new OrderDetailsInfo(UUID.fromString(cest.getJSONObject(i).getString("OrderID"))
, dateOrder,
cest.getJSONObject(i).getString("BrancId"),
cest.getJSONObject(i).getString("DCBranchID"),
cest.getJSONObject(i).getString("OrderDocNo"),
cest.getJSONObject(i).getString("SubdealerID"),
cest.getJSONObject(i).getString("DocOrderNo"),
cest.getJSONObject(i).getString("OrderDocNoAlt"),
cest.getJSONObject(i).getString("SalesChannelID"),
cest.getJSONObject(i).getString("MarketingProgramID"),
cest.getJSONObject(i).getString("MDMarketingProgramID"),
cest.getJSONObject(i).getString("PriceListID")));
}
OrderDetailsAdapter adapter = new OrderDetailsAdapter(getActivity(), mDetail);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
Toast.makeText(getActivity().getApplicationContext(), "Refreshed: " + cest.length(), Toast.LENGTH_LONG).show();
} //if (cast != null) {
} //if (!obj.getBoolean("error")) {
} catch (JSONException e) {
}
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable e, JSONObject errorResponse) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
// Probable causes: no internet permission, no internet connection
Toast.makeText(getActivity().getApplicationContext(), "error: onFailure: " + e.toString(), Toast.LENGTH_LONG).show();
}
});
}
When i run this there no eror but the data cannot be load..
What wrong with my code.?
Somebody please help me..

LoopJ AndroidAsyncHttp PUT, how to do?

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

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

Categories

Resources