i trying to connect my project in android studio to Asp.net API
and i'm using Volley Lib to Get Json Request but he did'nt read the response
and I getting this massage in Log
((( E/Volley: [352] BasicNetwork.performRequest:
Unexpected response code 400 for http://10.10.4.150:61511/api/Feedback/30)))
-Api work correctly i`m test with postman
enter image description here
public static final String GET_BY_ID = "http://10.10.4.150:61511/api/Feedback/30";
EditText id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
id = (EditText) findViewById(R.id.idtxt);
}
public void click(View v) {
if (v.getId() == R.id.btnget) {
insertData (id.getText().toString()) ;
}
}
public void insertData (String value){
HashMap<String,String> param = new HashMap<String, String>();
param.put("id",value);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, GET_BY_ID,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
JSONObject ob = response.getJSONObject("userId") ;
int name = ob.getInt("userId");
Toast.makeText(getBaseContext(),name,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getBaseContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("User-agent", "My useragent");
return headers;
}};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
}
Related
i have a server side api method which accept Model class as a parameter
which does work fine i have checked it but from android i am confused how to send a Model class as a parameter?
public class Login extends AppCompatActivity {
EditText email, password;
String Email, Pass;
Button loginbtn;
String URL = "https://192.168.0.102/api/campaign/Logins";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
handleSSLHandshake();
email = findViewById(R.id.input_email);
password = findViewById(R.id.password);
loginbtn = findViewById(R.id.login_button);
final RequestQueue queue = Volley.newRequestQueue(this);
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Email = email.getText().toString();
Pass = password.getText().toString();
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", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
params.put("email", Email);
params.put("password", Pass);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
queue.add(postRequest);
}
});
This is what i have tried i know the problem is from the server side can anyone help me what i am thinking is the problem or is there anything else ?
You just need to add a JSONObject with the post parameters as key-value pairs in the JSON Object. Here is the example for you:
JSONObject postparams = new JSONObject();
postparams.put("keyX", "valueX")
postparams.put("KEY", "Value")
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, postparams,
new Response.Listener() {
#Override
public void onResponse(JSONObject response) {
//Success Callback
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Failure Callback
}
});
I am trying to send data to server using Volley and I couldn't able to retrive the data from server, below is my volley code -
final RequestQueue Q = Volley.newRequestQueue(MainActivity.this);
//Handler h = new Handler();
final JsonObjectRequest get_j = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
//set_t();
public void onResponse(JSONObject response) {
try {
Q.stop();
//t.setText(response.getString("ip"));
if(response.getString("STATUS").equals("PASS")){
t.setText(response.getString("ID"));
}
else{
t.setText("Oops..! Some thing went wrong");
}
} catch (JSONException e) {
t.setText("Error...");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Q.stop();
t.setText(error.getMessage());
error.printStackTrace();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String,String>();
params.put("ADDRESS_TYPE","3");
params.put("DOOR_NO","XYZ/123");
return params;
}
};
Q.add(get_j);
And below is the code of PHP Server -
<?php $data["STATUS"] = "PASS"; $data["ID"] = "xx".$_GET['DOOR_NO']; echo json_encode($data); ?>
I am using android volley library to post data to back-end service. But I can't send any parameter with my request. I have done each and everything mentioned here . But none works for me. The post method that I am using is:
public static void post()
{
// Tag used to cancel the request
String tag_json_obj = "json_obj_req";
String url = "http://myUrl";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
return headers;
}
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("key", "value");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
Always the response is "parameter missing".
How could i resolve this issue?
If you're using JSONObjectRequest, you can try this.
String url = "http://myurl";
Map<String, String> params = new HashMap<String, String>();
params.put("key", value);
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
url, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
try {
success = jsonObject.getInt("success");
message = jsonObject.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Activity activity = getActivity();
if (volleyError instanceof NoConnectionError) {
String errormsg = "Check your internet connection";
Toast.makeText(activity, errormsg, Toast.LENGTH_LONG).show();
}
}
});
queue.add(jsonObjectRequest);
The codes are more likely the same as yours. Check on the lines where I put the data to be posted. I'm very sure this would work!
The problem is you are approaching the request as though you were making a stringRequest. The link you reference is talking specifically about making a stringRequest.
jsonObjectRequest actually lets you put the json object into the constructor itself, instead of using the override method getParams() like so:
String url = "some_url";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put(Constants.LOGIN_EMAIL_ID, email);
jsonObject.put(Constants.LOGIN_PASSWORD, password);
}catch(JSONException e){
Log.d("JSON error", e.getMessage(), e);
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("RESPONSE", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(error.getMessage()!=null){
Log.d("RESPONSE", error.getMessage());
}
}
});
VolleySingleton.getInstance(activity).getRequestQueue().add(jsObjRequest);
i am struggling to make this work, basically i get an id from previous activity using intent, now i want to send this id to server so it returns all the data associated with this id.
javacode
final String URL = "URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("ID", "1");
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
print response in textview;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
PHP server
if (!empty($_POST)) {
$query = " SELECT * FROM table WHERE ID = :ID " ;
$query_params = array(
':ID' => $_POST['ID'],);
try {
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database query error";
die(json_encode($response));
}
$result = $statement->fetchAll();
if($result){
$data =array();
foreach($result as $rows){
$json = array();
$json["Name"] = $rows["Name"];
array_push ($data,$json);
}
echo stripcslashes(json_encode($data, JSON_PRETTY_PRINT));
i used this example of http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put and coverted the string response to string array, worked for me
url = "http://httpbin.org/post";
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("name", "Alif");
params.put("domain", "http://itsalif.info");
return params;
}
};
queue.add(postRequest);
I would modify the request like this:
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,URL,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
print response in textview;
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("ID", "1");
return params;
}
};
ApplicationController.getInstance().addToRequestQueue(req);
and also would modify the PHP code like this:
if (isset($_POST['ID'])) {
$id = $_POST['ID'];
try {
$statement = $db->prepare(SELECT * FROM table WHERE ID = ?);
$statement->bindValue(1, $id);
$result = $statement->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database query error";
die(json_encode($response));
}
$records = array();
$records = $statement->fetchAll(PDO::FETCH_ASSOC);
$data = array();
foreach($records as $record){
$data["Name"] = $record["Name"];
}
echo stripcslashes(json_encode($data, JSON_PRETTY_PRINT));
}
Hope it helps!!!
the issue is that you send json but you expect params in you php.
there 2 solutions:
1) update php to accept json not just post params
2) update volley request to send post params but expect JSONObject
for example you can use this request:
public class JsonObjReq extends Request<JSONObject> {
private final Response.Listener<JSONObject> mListener;
private final Map<String, String> params;
public JsonObjReq(int method, String url, Map<String, String> params, Response
.Listener<JSONObject> mListener,
Response.ErrorListener listener) {
super(method, url, listener);
this.mListener = mListener;
this.params = params;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
mListener.onResponse(response);
}
}
and apply to your code like that:
final String URL = "URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("ID", "1");
JsonObjReq req = new JsonObjReq(Method.POST, URL, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
print response in textview;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
in volley we have some ability to retrieve data from server such as jsonObject,jsonArray and String. in this below sample we can get simply jsonObject or jsonArray response from server,
public static void POST(HashMap<String, String> params, final Listeners.ServerResponseListener listener) {
JsonObjectRequest req1 = new JsonObjectRequest(ApplicationController.URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("Response:", response.toString());
if (listener != null)
listener.onResultJsonObject(response);
else
Log.e(TAG,"Error: SetServerResponse interface not set");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error: ", error.getMessage());
}
});
ApplicationController.getInstance().addToRequestQueue(req1);
}
my problem is i want to send jsonObject from this method and get jsonArray or jsonObject from server, and i can not get simply array from server with this method. for example i must be filter server response with this jsonObject:
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");
params.put("search_count", "10");
params.put("order_by", "id");
server return jsonArray and i can not get that with Volley response
Looking at the source code of JsonArrayRequest. There is a constructor which takes in a JSONObject. You should check it out
public class RetreiveData {
public static final String TAG = RetreiveData.class.getSimpleName();
public static void POST(String localhost, final HashMap<String, String> params, final Listeners.ServerResponseListener listener) {
StringRequest post = new StringRequest(Request.Method.POST, localhost, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
if (listener != null)
listener.onResponse(response.toString());
else
Log.e(TAG, "Error: SetServerResponse interface not set");
} catch (Exception e) {
e.printStackTrace();
Log.d("Error: ", e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error: ", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = params;
return map;
}
#Override
public RetryPolicy getRetryPolicy() {
setRetryPolicy(new DefaultRetryPolicy(
5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
return super.getRetryPolicy();
}
};
ApplicationController.getInstance().addToRequestQueue(post);
}
}