HTTP POST request with different format of the url - android

I am developing an Android app for a Company. While working on the API the company guys gave me a login API something like this
"app.abc.com/Login?data={"email":"abc","pwd":"123"} "
I am using volley library but I don't know how to post data like this since I have not done it before.
I need advice and wanted to know if this is the right way.

Instead of volley ..try to use android networking library
--to do this :add
--compile 'com.amitshekhar.android:android-networking:0.4.0'
to your gradle file.enter code here
AndroidNetworking.post("your login URL")
.setTag("Login")
.addBodyParameter("email", "abc")
.addBodyParameter("pwd", "123")
.setPriority(Priority.IMMEDIATE)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject dataJson = response.getJSONObject("data");
boolean status = dataJson.getBoolean("success");
} else {
JSONArray errorJsonArray = dataJson.getJSONArray("errors");
String errorMsg;
for (int i = 0; i < errorJsonArray.length(); i++) {
errorMsg = errorJsonArray.get(i).toString();
Toast.makeText(LoginActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
}
Log.e("Error", response.toString());
}
} catch (JSONException je) {
je.printStackTrace();
}
}
#Override
public void onError(ANError anError) {
try {
if (anError.getErrorBody() != null) {
JSONObject jsonObject = new JSONObject(anError.getErrorBody());
JSONObject dataJsonObject = jsonObject.getJSONObject("data");
Toast.makeText(getApplicationContext(), dataJsonObject.getString("message"), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), anError.getErrorDetail(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
Log.e("Error", anError.getErrorDetail());
}
});

Using Volley - Create the request queue
RequestQueue queue = Volley.newRequestQueue(this); // this = context
Then create the postRequest, should look somthing like (using Volley):
url = "app.abc.com/Login";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("data", "{\"email\":\"abc\",\"pwd\":\"123\"}");
return params;
}
};
queue.add(postRequest);
I also recommend using Retrofit and GSON libraries (a bit learning curve here but it is worth it since they are very powerful libraries)

Related

Server responce is in json form

I want to send and receive data from server. For this I've used Volley. The code is in below. Volley can receive the data in Json format. The Server can send and receive data in Json format. How do I convert this Json data into a user readable JAVA format ?? There are about 10 methods in other class. The below class contains the methods for network calls and also interacts with the MainActivity.
public class Api_Volley {
String data;
String flag;
public void my_volley_post (String url , JSONObject jsonObject , final Context context ) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url , jsonObject , new Response.Listener(){
#Override
public void onResponse(Object response) {
String flag = response.toString();
Toast.makeText( context , flag , Toast.LENGTH_LONG ).show();
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context , "Wrong" , Toast.LENGTH_LONG).show();
error.printStackTrace();
}
});
ApiVolleySingeltonClass.getInstance(context).addToRequestque(jsonObjectRequest);
}
}
Methods in another class:
public void showAllOrderByUserId() {
try {
data_args.put("userId", 2);
} catch (JSONException e) {
e.printStackTrace();
}
try {
data_action.put("action", "showAllOrderByUserId");
data_action.put("args", data_args);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
route = "/order";
new Api_Volley().my_volley_post(addUserUrl + route, data_action, context);
}
Your can use json data like
{"userNodes":[{"id":"1","name":"Enamul Haque"}]}
You can use volley like bellow
private void doLoginAction() {
String url_login = "http://www.lineitopkal.com/android/login.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_login,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//pDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray loginNodes = jsonObject.getJSONArray("userNodes");
for (int i = 0; i < loginNodes.length(); i++) {
JSONObject jo = loginNodes.getJSONObject(i);
String id = jo.getString("id");
Log.e("id ::",id);
String name = jo.getString("name");
Log.e("name ::",name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
try {
if (error instanceof TimeoutError ) {
//Time out error
}else if(error instanceof NoConnectionError){
//net work error
} else if (error instanceof AuthFailureError) {
//error
} else if (error instanceof ServerError) {
//Erroor
} else if (error instanceof NetworkError) {
//Error
} else if (error instanceof ParseError) {
//Error
}else{
//Error
}
//End
} catch (Exception e) {
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
//Post parameter like bellow
params.put("uname", "era#gmail.com");
params.put("pass", "123456");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Create your Response format like this
public class Post {
long id;
Date dateCreated;
String title;
String author;
String url;
String body;
}
After making request like below
public void my_volley_post (String url , JSONObject jsonObject , final Context context ) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url , jsonObject , new Response.Listener(){
#Override
public void onResponse(String response) {
GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
// This will be your Entity
Post post = gson.fromJson(response, Post.class));
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context , "Wrong" , Toast.LENGTH_LONG).show();
error.printStackTrace();
}
});
ApiVolleySingeltonClass.getInstance(context).addToRequestque(jsonObjectRequest);
}
You have to parse JSON and have to show according to need:
By this you can use GSON (Its easy)
Use this Site to convert JSON to pojo classes.
Click here
These are the References site you can use and implement :
http://www.vogella.com/tutorials/JavaLibrary-Gson/article.html
https://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
https://kylewbanks.com/blog/tutorial-parsing-json-on-android-using-gson-and-volley

sending username and password via post request in volley in android

I am using this url to send post reqeust via volley:"http://136.243.146.41:8443/api/GetMainCategories".
here is my code:
void MakePostRequest() {
StringRequest postRequest = new StringRequest(Request.Method.POST, mainmenurl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject("{response}");
//makemainmenulist();
Toast.makeText(Cofeelist.this,"success!--->>>>"+response, Toast.LENGTH_LONG).show();
Log.i("sucsses!.....",response);
// value1= jsonResponse.getString("Your ID1");
// value2= jsonResponse.getString("Your ID2");
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(Cofeelist.this,"error1!--->>>>"+e, Toast.LENGTH_LONG).show();
Log.i("Error1!.....",e+"");
// banner_id = null;
// full_id = null;
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(Cofeelist.this,"error2!--->>>>"+error, Toast.LENGTH_LONG).show();
Log.i("error2!.....",error+"");
// value1= null;
// value2= null;
}
}
) {
// here is params will add to your url using post method
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("username", "pourya");
params.put("key", "54a65sdf4a35s4d");
return params;
}
};
Volley.newRequestQueue(this).add(postRequest);
}
but i got this error:"com.android.volley.NoConnectionError: java.io.EOFException ".i changed the url to"tarkhinehapp/api/GetMainCategories" but i got another error " com.android.volley.ServerError"
Have you checked the server log?
I used volley lib to connect to server and sent username and pass via querystring in url as below:
MyVolleyStringRequest mainmenureq=new MyVolleyStringRequest(Request.Method.GET, G.urlBase+"MainCategoriesApi?username="+"username"+"&"+"key="+"pass",new MyListener(this));
the volley made my job so easy!

How to send Json POST request using Volley in android in the Given Tutorial?

Hi I am a beginner in Android , I am learning to make Api Calls. I got a tutorial of Volley which uses GET to Receive response. Now I want to Send Post request Using Volley. I don't know how to do that, what would be the code for POST in the given Tutorial. Please guide me to send Post Request.The link to the tutorial that I am learning is http://www.truiton.com/2015/02/android-volley-example/
you have to used below code to send request
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
try {
/** json object parameter**/
JSONObject jsonObject = new JSONObject();
jsonObject.put("hello", "hello");
Log.e("jsonObject params", jsonObject.toString() + "");
/**URL */
String url ="http://google.com"
progress.setVisibility(View.VISIBLE);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
progress.setVisibility(View.GONE);
Log.e(TAG, "Response " + jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
progress.setVisibility(View.GONE);
Log.e(TAG, volleyError);
Util.showToast(activity, "Please try again");
}
});
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
progress.setVisibility(View.GONE);
Log.e(TAG, e);
}
catch (Exception e) {
progress.setVisibility(View.GONE);
Log.e(TAG, e);
}
}
}
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jsonObjectRequest);
You can follow this :http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
StringRequest request = new StringRequest(Method.POST,
"post url",
new ResponseListener() {
#Override
public void onResponse(String response) {
Log.d("response", response);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("response","error");
}
}) {
// post params
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param", "param");
return params;
}
};
//2.Use your custom volley manager send request or like this
Volley.newRequestQueue(mCtx).add(request);

Adding POST parameters to Android Volley JsonObjectRequest

Good afternoon everyone
I did a volley connection to my localserver. It turns out, the connection works fine but my parameters are not getting accepted in my MysqlPHP script.
I believe the parameters are not getting sent correctly.
Here is the code
try {
RequestQueue jr = Volley.newRequestQueue(this);
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
Log.d("The paramet ready", "Ready to go");
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("The response", response.toString());
progressDial.hide();
JSONArray json = null;
try {
json = response.getJSONArray("result");
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (json.getString(0).equalsIgnoreCase("0")) {
Log.d("JsonString: -> ", json.toString());
progressDial.hide();
toast();
} else {
startagain();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
progressDial.hide();
}
}
);
jr.add(jsonObject);
I encountered a similar issue. I had a server API which returned a JSON Object response, so JsonObjectRequest was the go-to request type, but the server didn't like that my body was in JSON format, so I had to make a few changes to my request.
Here's what I did (adapted to your code):
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.POST, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("The response", response.toString());
progressDial.hide();
JSONArray json = null;
try {
json = response.getJSONArray("result");
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (json.getString(0).equalsIgnoreCase("0")) {
Log.d("JsonString: -> ", json.toString());
progressDial.hide();
toast();
} else {
startagain();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
progressDial.hide();
}
}
)
{
#Override
public byte[] getBody()
{
try
{
final String body = "&username=" + username + // assumes username is final and is url encoded.
"&password=" + password // assumes password is final and is url encoded.
return body.getBytes("utf-8");
}
catch (Exception ex) { }
return null;
}
#Override
public String getBodyContentType()
{
return "application/x-www-form-urlencoded";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
return headers;
}
};
Here, I'm not sending any JSON Object as the post body, but instead, I'm creating the post body on my own, form url encoded.
I'm overriding the following methods:
getBody - I'm creating the body of the post exactly the way the server wanted it - form url encoded.
getBodyContentType - I'm telling the server what the content type of my body is
getHeaders - I'm telling the server to return the result in JSON format. This might not be necessary for you.
If your API return a JSON array, then you should use a JsonArrayRequest, not a JsonRequest.

Android Volley. JsonArray JsonException end of input at character 0

I'm trying to retrieve a jsonarray from a url using Volley.
the problem is that I get
JsonException end of input at character 0
the code is the following:
JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST, openMatchesUrl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("JSON", response.toString());
try {
for (int i = 0; i < response.length(); i++) {
//do stuff
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
"onErrorResponse ongoing: "+error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams()
{
//build params
}
};
// Add the request to the RequestQueue.
queue.add(req);
I was thinking that the problem was in wrong parameters. but I tried with a simple string request:
StringRequest req = new StringRequest(Request.Method.POST, openMatchesUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("JSON", "resp: " +response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("JSON", error.toString());
}
}){
#Override
protected Map<String, String> getParams()
{
//build params
}
};
and it's actually returning the json correctly. for example:
[{"roundid":4152,"numberofplayers":1,"dateevent":"2015-04-13 19:45:32.121124+02","playernames":"cat","turn":1,"codedboard":""},{"roundid":415‌​4,"numberofplayers":1,"dateevent":"2015-04-13 20:16:08.845409+02","playernames":"cat","turn":1,"codedboard":""},{"roundid":415‌​5,"numberofplayers":1,"dateevent":"2015-04-13 20:18:22.002411+02","playernames":"cat","turn":1,"codedboard":""}]
what's the problem here?
Total shot in the dark, but I had similar occur on an RSS parser. It turns out the URL I was using was HTTP, but redirected to HTTPS and I was using an HttpURLConnection instead of HttpsURLConnection.
Though, I wasn't using Android Volley so YMMV.
I finally solved this, the problem here is that for some reason JSonArrayRequest was not taking the POST parameters.
So I just manually appended the parameters to the url

Categories

Resources