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.
Related
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();
}
});
I m posting JSON in raw with this Url [URL I post data to][1]
param is=eventName="countryList"
codes
private void testApp() {
try {
JSONObject jsonParams = new JSONObject();
jsonParams.put("key", "value");
StringEntity entity = new StringEntity(new Gson().toJson(jsonParams));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
AsyncHttpClient client = new AsyncHttpClient();
client.post(getApplicationContext(), "url", entity, "application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
super.onSuccess(statusCode, headers, response);
Log.e("good",response.toString());
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e("fail",throwable.toString());
}
});
} catch (Exception e) {
}
}
error:fail: cz.msebera.android.httpclient.client.HttpResponseException: Internal Server Error
change fromStringEntity entity = new StringEntity(new Gson().toJson(jsonParams));
to:**StringEntity stringEntity = new StringEntity(jsonParams.toString());**
And Also override
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
}
your response return jsonobject not array
With all the old methods been deprecated such as http post , response ,http client, string entity etc, i want to know how can i post json data to a server in android in 2017. My app is supposed to register or send JSON data such as email,contact number and password to a server using POST method and in turn server will give JSON response such as status , message and an array named data. Data is an array of only 2 objects (ie token and email). Please Help.
I think you need to try Loopj library for sending Json Data
you can try this link
and also it is quite easy to undestand
You can try another link
try{
AsyncHttpClient client = new AsyncHttpClient();
JSONObject obj = new JSONObject();
obj.put("email",email);
obj.put("contact_number",contact_number);
obj.put("password",password);
entity = new StringEntity(obj.toString());
client.post(getApplicationContext(), "Your_URL", entity, "application/json", new TextHttpResponseHandler() {
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.d("LoginActivity","Failed");
Log.d("LoginActivity","body " + responseString);
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
Log.d("LoginActivity","data " + responseString);
try {
JSONObject respObj = new JSONObject(responseString);
String data = respObj.toString();
Log.d("LoginActivity","Data : " + data);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}catch (Exception ex){
Log.d("LoginActivity","Getting Exception "+ex.toString());
}
Try like this
private void registerUser(){
final String username = editTextUsername.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
final String email = editTextEmail.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERNAME,username);
params.put(KEY_PASSWORD,password);
params.put(KEY_EMAIL, email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Hey i'm using AsynHttpClient.
I would like to implement my get and set functions in one Activity where they can get called by others.
But how can i call my custom callback from the reponse callback?
I dont get it how it works in an inner class
public void requestApiUrl(Callback callback ){
JSONObject jsonObj = new JSONObject();
try {
jsonObj.put("AppKey",getResources().getString(R.string.AppKey));
AsyncHttpClient client = new AsyncHttpClient();
StringEntity entity = null;
try {
entity = new StringEntity(jsonObj.toString());
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
client.get(this, "***************URL***********", entity, "application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject utils) {
super.onSuccess(statusCode, headers, utils);
Log.d("HTTP", "response: " + utils.toString());
callback.reponse();
}
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.d("Failed: ", "" + statusCode);
Log.d("Error : ", "" + throwable);
callback.reponse();
}
});
}catch (JSONException e) {
e.printStackTrace();
}
}
As far as i could get out of your question, you need to call a function from child/inner class where the function belongs to the parent/outer class. Quoting the answer from this question
For a class
class Outer {
void show() {
System.out.println("outter show");
}
class Inner{
void show() {
System.out.println("inner show");
}
}
}
you can simply call
Outer.this.show();
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>");
}
}