String request return null output in android studio when i used jsonobject request it will give correct output.
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
Log.d(TAG, " url=" + URL);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, " response=" + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, " error=" + error);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
LinkedHashMap<String, String> linkmap = new LinkedHashMap<>();
linkmap.put("p_ENTITY_ID", "2");
linkmap.put("p_ORGCD", "p01");
linkmap.put("p_COMPCD", "A0002");
linkmap.put("p_DIVCD", "");
linkmap.put("p_USERID", "");
linkmap.put("p_ACDYR", "");
linkmap.put("p_TYPE", "ACDYR_DDL");
linkmap.put("p_FILTER1", "");
linkmap.put("p_FILTER2", "");
linkmap.put("p_DEFUNCT", "");
Log.d(TAG, " MAP=" + linkmap);
return linkmap;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
LinkedHashMap<String, String> headers = new LinkedHashMap<>();
return headers;
}
};
requestQueue.add(stringRequest);
}
Related
I'm passing a key-value pair in String request using post request method I'm getting error 400.
The Error is:E/Volley: [1120] NetworkUtility.shouldRetryException: Unexpected response code 400 for http://11.1.1.86:9000/cef/investmentStrategies/android
RequestQueue MyRequestQueue = Volley.newRequestQueue(getContext());
url5 = "http://11.1.1.86:9000/cef/investmentStrategies/android";
StringRequest stringRequest5 = new StringRequest(Request.Method.POST, url5, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("No Error");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error is here..");
}
}) {
#Nullable
#Override
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("Field",id);
return MyData;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
MyRequestQueue.add(stringRequest5);
}
I get the following error:
AuthFailureError: com.android.volley.AuthFailureError
My code:
public void createNoticeBoard() {
RequestQueue queue = Volley.newRequestQueue(mContext);
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.PENDING_MEDIA_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject stringResponse = new JSONObject(response);
boolean success = stringResponse.getBoolean("is_success");
String requestCode = stringResponse.getString("status_code");
if (success) {
if (requestCode.equals("200")) {
Toast.makeText(mContext, "Publisher deleted!", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(mContext, "Unauthorized!", Toast.LENGTH_LONG).show();
}
} catch (JSONException je) {
je.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.e(TAG, "AuthFailureError: " + error);
Toast.makeText(mContext, "Error! Please try again.", Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> parameter = new HashMap<>();
Log.d("Network", parameter.toString());
return parameter;
}
#Override
protected Map<String, String> getParams() {
Map<String,String> params = new HashMap<String, String>();
params.put("extension", "image/jpeg");
params.put("duration", String.valueOf(20));
params.put("title", "Postman Highlight");
params.put("organization_id", String.valueOf(274));
params.put("screen_type", "TAGNOTICEBOARD");
params.put("type", "IMAGE");
params.put("do", String.valueOf(7));
params.put("advertise_bit", String.valueOf(1));
params.put("start_datetime", "2021-05-06 10:37:13");
params.put("end_datetime", "2021-05-10 10:37:13");
params.put("Global_Counter", String.valueOf(0));
params.put("Venue_Counter", String.valueOf(0));
params.put("adindex", String.valueOf(0));
params.put("adtype", "Fulltime");
params.put("media_url", "");
return params;
}
#Override
public byte[] getBody() throws AuthFailureError {
final String request = getParams().toString();
Log.e("REQ", request);
try {
return request.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", request, "utf-8");
return null;
}
}
};
queue.add(stringRequest);
}
I am a complete noob to Android Studio, Java and Stack Overflow. My app performs a lot of HTTP Post requests using Volley and hence I've made an independent Java class with the code to perform the post request.
public class HTTPReq {
String[] finalResponse = new String[1];
public String postRequest(final HashMap<String,String> params, final Context context) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
String url = "https://reqres.in/api/login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
finalResponse[0] = response;
Toast.makeText(context, "2" + finalResponse[0], Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
finalResponse[1] = error.getMessage();
//Toast.makeText(context, "Response Failed", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
requestQueue.add(stringRequest);
Toast.makeText(context, "3" + finalResponse[0], Toast.LENGTH_LONG).show();
return finalResponse[0];
}
}
What I'm trying to achieve is to get the response of the http request to the function call using return.
The function call is as follows:
public void login(String phno, String password,Context context)
{
HashMap<String,String> credentials = new HashMap<String, String>();
credentials.put("email","eve.holt#reqres.in");
credentials.put("password","cityslicka");
HTTPReq httpReq = new HTTPReq();
String response = httpReq.postRequest(credentials,context);
Toast.makeText(context, "1" + response, Toast.LENGTH_LONG).show();
}
I hope it's clear what I'm trying to achieve. Please help me with this.
your con use feature interface
public class HTTPReq {
public void postRequest(final HashMap<String, String> params, final Context context, final ResponseCallBack callBack) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
String url = "https://reqres.in/api/login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
callBack.onResponse(response);
Toast.makeText(context, response, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callBack.onError(error);
Toast.makeText(context, "Response Failed", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
requestQueue.add(stringRequest);
}
}
calss interface :
import com.android.volley.VolleyError;
public interface ResponseCallBack<T> {
public void onResponse(T response);
public void onError(VolleyError error_response);
}
MainActivity:
public class MainActivity extends AppCompatActivity implements ResponseCallBack {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HTTPReq httpReq = new HTTPReq();
HashMap<String, String> credentials = new HashMap<String, String>();
credentials.put("email", "eve.holt#reqres.in");
credentials.put("password", "cityslicka");
httpReq.postRequest(credentials, this, this);
}
#Override
public void onResponse(Object response) {
Log.e("TAG", "onResponse: " + response);
}
#Override
public void onError(VolleyError error_response) {
Log.e("TAG", "onError: " + error_response);
}
I am trying to send a post request to my server
my server read Headers of the request in String Format but getHeaders() in Volley return : Map< String, String >
Is there any way to send headers of request in string Format ?!
this is my Code Request :
Map<String, String> params = new HashMap<String, String>();
params.put("MY_FIRST_DATA_KEY", "MY_FIRST_DATA_VALUE");
params.put("MY_SECOND_DATA_KEY", "MY_SECOND_DATA_VALUE");
String url = "http://MY_URL.com";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "onResponse: " + response.toString() );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: " + error.toString() );
error.printStackTrace();
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("MY_KEY","MY_VALUE");
/* HERE i need to return a String Value */
return headers;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(20000 , 3 , 3));
Volley.newRequestQueue(context).add(request);
try overriding getParams()
#Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("MY_FIRST_DATA_KEY", "MY_FIRST_DATA_VALUE");
params.put("MY_SECOND_DATA_KEY", "MY_SECOND_DATA_VALUE");
return params;
}
You can add getParams() in the JsonObjectRequest()
#Override
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Parameter1", "value");
params.put("Parameter2", "value");
return params;
}
Hope it helps.
This is how I made a volley POST request adding headers and body
private void call_api(final String url){
if(!this.isFinishing() && getApplicationContext() != null){
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
resultsTextView.setVisibility(View.INVISIBLE);
loader.setVisibility(View.VISIBLE);
}
});
Log.e("APICALL", "\n token: " + url);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("APICALL", "\n response: " + response);
if(!FinalActivity.this.isFinishing()){
try {
JSONObject response_json_object = new JSONObject(response);
JSONArray linkupsSuggestionsArray = response_json_object.getJSONObject("data").getJSONArray("package");
final JSONObject k = linkupsSuggestionsArray.getJSONObject(0);
final String result = k.getJSONArray("action").getJSONObject(0).getString("url");
last_results = result;
last_results_type = k.getString("type");
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
loader.setVisibility(View.INVISIBLE);
resultsTextView.setText(result);
resultsTextView.setVisibility(View.VISIBLE);
}
});
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "An unexpected error occurred.", Toast.LENGTH_LONG).show();
finish();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("APICALL", "\n error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Check your internet connection and try again", Toast.LENGTH_LONG).show();
finish();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("apiUser", "user");
headers.put("apiKey", "key");
headers.put("Accept", "application/json");
//headers.put("Contenttype", "application/json");
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<>();
map.put("location", "10.12 12.32");
return map;
}
};
stringRequest.setShouldCache(false);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
Am trying to send String and int as params in volley. But it show error on String if i use Map<String,Integer> params = new HashMap<String, String>(); and show error on int if i use Map<String,String> params = new HashMap<String, String>(); So how can i send int and String as a param in post request.
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://www.aaa.com/insert/signup" ,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("sign_up_res", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error" , error.toString());
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("firstname" , PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString(Local_Preference.FIRSTNAME, "Not Set") );
params.put("number" , "123");
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
1000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(SignUp2Activity.this);
requestQueue.add(stringRequest);
In Sql table is like firstname (varchar) and number(int). I don't want to change the int type to varchar in sql. Is there any way to send int and String in a single params.
you can do this create a
Map params = new HashMap();
then
params.put(key,value); // for string
params.put(key,String.valueOf(value)); // for int As suggested
Please follow the code using this my problem is solved
String tag_json_obj = "json_obj_req";
String url = "https://api.androidhive.info/volley/person_object.json";
ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("name", "Androidhive");
params.put("email", "abc#androidhive.info");
params.put("password", "password123");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);