I have a students table.
I am trying to send request to and REST APP using the HTTPS and JSON Array from the Android studio to My web-based application.
My request works fine.
The problem I am getting is how to send params in the request.
public void SyncRoutsAfterExport(){
//Send request to server to get routes
//Request que
RequestQueue mQueue = Volley.newRequestQueue(UserProfile.this);
//Json perse function
String url = "xxxxxxxxxxxxxxxxxx";
Map<String, String> params = new HashMap<String, String>();
params.put("name", "mark");
params.put("nam", "someOtherVal");
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++){
try {
JSONObject jresponse = response.getJSONObject(i);
String name= jresponse.getInt("name");
String age= jresponse.getString("age");
AddDatatotable(name,age);
if(i == response.length() -1){
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
so In the above code, I want to send couple of params name and age. How to send the above request with params.
I think you can try StringRequest and overload getParams Method
RequestQueue mQueue = Volley.newRequestQueue(UserProfile.this);
//Json perse function
String url = "xxxxxxxxxxxxxxxxxx";
Map<String, String> params = new HashMap<String, String>();
params.put("name", "mark");
params.put("nam", "someOtherVal");
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String requestResponse) {
JSONArray response
try {
array=new JSONArray(requestResponse);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < response.length(); i++){
try {
JSONObject jresponse = response.getJSONObject(i);
String name= jresponse.getInt("name");
String age= jresponse.getString("age");
AddDatatotable(name,age);
if(i == response.length() -1){
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
};
mQueue.add(request);
Related
I am trying to get a string response from post request. Here, I am sending a post request. where I am sending this data. I have a Model of BillReceipt. Which I pass on the request body.
public void UserTransactionReceiptReport(TransactionTypeListener<String> listener, BillReceipt billReceiptReport){
final UserSettings userSettings = getMUserSettings();
final StringBuilder url = new StringBuilder(AppConfigsManager.getTouchServerUrl());
url.append("/api/User/UserData");
JSONObject params = new JSONObject();
try{
params.put("iB_CUST_ID",billReceiptReport.getiB_CUST_ID());
params.put("transactioN_DATE",billReceiptReport.getTransactioN_DATE());
params.put("transactioN_DATE_NM",billReceiptReport.getTransactioN_DATE_NM());
}catch (Exception e){
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url.toString(), params
, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Gson mapper = new GsonBuilder().create();
try{
Type type = new TypeToken<APIResponse<String>>() {
}.getType();
APIResponse<String> responseObject = mapper.fromJson(response.toString(), type);
if(responseObject.Status == APIStatus.OK){
listener.didFetch(responseObject.Result, responseObject.Message);
}else {
listener.didError(responseObject.Message);
}
}catch (Exception e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.didError(error.getMessage());
}
})
{
#Override
public Map<String, String> getHeaders() {
return getAuthorizationTokenHashMap(getMUserSettings());
}
};
addVolleyRequest(request);
}
and I call this api from recycler download button.Here , I globally declared the manager where i write the api code. and also declare a the model name.
holder.downloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
manager.UserTransactionReceiptReport(listener,billReceiptReport);
}
});
}
private final TransactionTypeListener<String> listener = new TransactionTypeListener<String>() {
#Override
public void didFetch(String response, String message) {
str = response;
}
#Override
public void didError(String message) {
}
};
any one help me to solve the problem i am facing.
Try this code
<code>
JSONObject jsonObject = new JSONObject(response);
System.out.println("jsonWallet----" + jsonObject);
int status_ = jsonObject.getInt("status");
if(status_ == 1){
String incomeWalletBal = jsonObject.getString("income_wallet");
String refundWalletBal = jsonObject.getString("refund_wallet");
}else {
}
</code>
E/Volley: [1888] BasicNetwork.performRequest: Unexpected response code 400 for https://pastebin.com/raw/2WMVsLei
Problem only Pastbin. I will try another https api but can't face any issue. Issue only occurs with pastebin api.
public void logIn() {
String URL="";
try {
JSONObject old = new JSONObject(Constantse.decrypt(PreferenceUtils.getAllData(con)));
String updateUrl = old.getString("DefUpdateURL");
URL = updateUrl;
}catch (Exception e){
System.out.println(e);
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject old = new JSONObject(Constantse.decrypt(PreferenceUtils.getAllData(con)));
JSONObject news = new JSONObject(Constantse.decrypt(response));
System.out.println(Constantse.decrypt(response));
if(Integer.parseInt(news.getString("UpdateVersion")) > Integer.parseInt(old.getString("UpdateVersion"))){
PreferenceUtils.setCredientials(con,news.getJSONArray("Servers").toString());
PreferenceUtils.setPayload(con,news.getJSONArray("payload").toString());
PreferenceUtils.setAllData(con,response);
editor.putInt("current_server", 0).apply();
editor.putInt("current_payload", 0).apply();
Toast.makeText(getActivity(),"Update Success",Toast.LENGTH_SHORT).show();
getActivity().finish();
startActivity(getActivity().getIntent());
}else{
System.out.println("Don't Update");
Toast.makeText(getActivity(),"Already Updated",Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
System.out.println(e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
logIn2(); // this is additional api for server & payload
Toast.makeText(getActivity(),"Use Next Server",Toast.LENGTH_SHORT).show();
System.out.println(error);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
stringRequest.setShouldCache(false);// for cash clear
Volley.newRequestQueue(con).add(stringRequest);
Volley.newRequestQueue(con).getCache().clear();// for cash clear
}
I want to call a Api But Reception error is running !!
I have a Json api
A Java class to call
Please help me fix the error!
my jeson:
my class in load data:
public void loadproductview() {
String url = "https://alphaonline.ir/index.php?route=api32/product/product&token=3344556677";
Response.Listener<JSONObject> objectListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String name = response.getString("name");
txt_name.setText(name);
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProductActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
}
};
Map<String, String> params = new HashMap();
params.put("product_id", "237");
JSONObject parameters = new JSONObject(params);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, parameters, objectListener, errorListener);
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(request);
}
You are initializing JSONObject with Map which is wrong>
Directly put the values in JSONObject.
JSONObject parameters = new JSONObject();
parameters.put("product_id", "237");
Try this:-
public void loadproductview() {
String url = "https://alphaonline.ir/index.php?route=api32/product/product&token=3344556677";
Response.Listener<JSONObject> objectListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String name = response.getString("name");
txt_name.setText(name);
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProductActivity.this, error.toString(),
Toast.LENGTH_SHORT).show();
}
};
JSONObject parameters = new JSONObject(params);
parameters.put("product_id", "237");
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL,
parameters, objectListener, errorListener);
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(request);
}
I am not sure how you handle the singleton instance of the request, so instead of this:
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(request);
do this:
RequestQueue queue = Volley.newRequestQueue(this);
queue.addToRequestQueue(request);
My JSON array don't work and I don't know why. In logs, it only show this: [] and nothing else. I won't use that in text view.
This is my code:
private void account(){
// get from the server
String url = "my url";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("uaccount");
Log.i("conso", jsonArray.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject employee = jsonArray.getJSONObject(i);
Log.i("con", employee.toString());
//Log.i("con", name+ number+status+ age+ city+ town+ gender+weight +height);
String city = employee.getString("city");
String town = employee.getString("town");
txt_City.setText(""+city);
txt_Town.append(town);
//Log.i("co", city + town);
}
} catch (JSONException e) {
Log.i("console.logs e:", e.toString());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("console.logs error:", error.toString());
error.printStackTrace();
}
});
requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(request);
}
i tried this code with id :
in onreate:
uAccount("3");
in method
private void uAccount(final String id){
// get from server
String url = "my url";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("uaccount");
Log.i("conso", jsonArray.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject employee = jsonArray.getJSONObject(i);
Log.i("con", employee.toString());
//Log.i("con", name+ number+status+ age+ city+ town+ gender+weight +height);
String city = employee.getString("city");
String town = employee.getString("town");
txt_City.setText(""+city);
txt_Town.append(town);
//Log.i("co", city + town);
}
} catch (JSONException e) {
Log.i("console.logs e:", e.toString());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("console.logs error:", error.toString());
error.printStackTrace();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("id",id);
return params;
}
};
requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(request);
}
I'm sending a post request to server using Volley request and i have some raw Type JSON data that has to be sent. Here I have no idea how to send the
4th object students which is type of Array.
JSON data to be posted is
{
"course_id":1,
"batch_id":1,
"subject_id":1,
"students":[{"student_id":6,"present":0},{"student_id":17,"present":0}]
}
My code
private void fetchDataAndMarkAttendence() {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
status = jsonObject.getString("status");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> map = new HashMap<String, String>();
SharedPreferences prefs = getApplicationContext().getSharedPreferences(MY_PREFS_NAME, Activity.MODE_PRIVATE);
token = prefs.getString("token","");
map.put("Authorization", "Token "+token);
return map;
}
}
}
So, any help regarding how can i post the JSON data mentioned above will be helpfull.
This is called JSONArray.
try {
JSONArray jsonArray = jsonObject.getJSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
int student_id = jsonObject.getInt("student_id");
int present = jsonObject.getInt("present");
}
} catch (JSONException e) {
e.printStackTrace();
}
EDIT
as mention, you want to post the json. So create the json suing below code and post mainJsonObject.toString(); as parameter.
try {
JSONObject mainJsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
//if more than one then wrap inside loop
JSONObject jsonObject = new JSONObject();
jsonObject.put("student_id", value);
jsonObject.put("present", value);
jsonArray.put(jsonObject);
//end loop
mainJsonObject.put("course_id", value);
mainJsonObject.put("batch_id", value);
mainJsonObject.put("subject_id", value);
mainJsonObject.put("students", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
hope it helps.
Replace your StringRequest with JsonObjectRequest
JSONObject postparams = new JSONObject();
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
}
});
can you try this? This probably will fix your problem.
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
status = jsonObject.getString("status");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
public byte[] getBody() throws AuthFailureError {
String yourJSON = yourJsonObj.toString() ;
return yourJSON.getBytes();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> map = new HashMap<String, String>();
SharedPreferences prefs = getApplicationContext().getSharedPreferences(MY_PREFS_NAME, Activity.MODE_PRIVATE);
token = prefs.getString("token","");
map.put("Authorization", "Token "+token);
return map;
}
};