class test2 : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_test2)
connect()
}
fun connect(){
val queue = Volley.newRequestQueue(this)
val url = "https://www.example.com/Register.php"
val params = HashMap<String,String>()
params["abc"] = "parm1"
params["def"] = "parm2"
params["ghi"] = "parm3"
val stringRequest = StringRequest(Request.Method.POST, url,
Response.Listener<String> { response ->
text_test.text = "Response is: $response"
},
Response.ErrorListener { text_test.text = "That didn't work! " })
queue.add(stringRequest)
}
}
The parameters should be in "param1=data1¶m2=data2¶m3=data3" format
I can send data in postmen using form-data
Any idea how i can send the data from my code?
Seriously please send help this is my second time asking
Here is the image for postman https://ibb.co/SQgG72W
You have to override getParams Method. In that you can pass your params you want to send to the server
StringRequest sr = new StringRequest(Request.Method.POST, "http://headers.jsontest.com/",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("HttpClient", "success! response: " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("HttpClient", "error: " + error.toString());
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("user","YOUR USERNAME");
params.put("pass","YOUR PASSWORD");
return params;
}
};
Related
I'm trying to send a POST request using Kotlin in Android. I need to use Volley and I need authentication with a bearer token. I don't know how to send the bearer token together with the post request.
val queue = Volley.newRequestQueue(this)
val parameters: MutableMap<String, String> = HashMap()
parameters.put("token_name", "app");
val strReq: StringRequest = object : StringRequest(
Method.POST, "https://url.com",
Response.Listener { response ->
try {
val responseObj = JSONObject(response)
val id = responseObj.getInt("id")
val token = responseObj.getString("name")
val tipo = responseObj.getString("email")
} catch (e: Exception) { // caught while parsing the response
}
},
Response.ErrorListener { volleyError ->
})
You can override the volley's request method:
public void requestWithSomeHttpHeaders(Context context) {
RequestQueue queue = Volley.newRequestQueue(context);
String url = "http://www.somewebsite.com";
StringRequest getRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// response
try {
JSONObject responseObj = new JSONObject(response);
int id = responseObj.getInt("id");
String token = responseObj.getString("name");
String tipo = responseObj.getString("email");
} catch (Exception e) { // caught while parsing the response
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.d("ERROR", "error => " + error.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
//insert your bearer token here
params.put("bearer token", "xxxxxx");
return params;
}
};
queue.add(getRequest);
}
Of course, you can read this post as a refer.
I have some code. In Volley code:
val queue = Volley.newRequestQueue(context)
val stringRequest = StringRequest(
Request.Method.GET,
linkTrang,
Response.Listener<String> { response ->
mTextView.text = "Response is: " + response.substring(0, 500));
},
Response.ErrorListener { })
{
}
queue.add(stringRequest)
How do I set a header called Authorization in this?
I was able to do it in Kotlin using:
val linkTrang = "YOUR URL"
val queue = Volley.newRequestQueue(this)
val stringRequest = object: StringRequest(Request.Method.GET, linkTrang,
Response.Listener<String> { response ->
Log.d("A", "Response is: " + response.substring(0,500))
},
Response.ErrorListener { })
{
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers["Authorization"] = "Basic <<YOUR BASE64 USER:PASS>>"
return headers
}
}
queue.add(stringRequest)
It is important to use the object keyword before the construction of the request in order to be able to override the getHeaders() method.
Having trouble on VolleyRequest getting always error response when loading it onCreate. I want to do is when the fragment loads. but when I try it, the Logcat gives me an error 400. on this Java class, i have another function that has sending data to API. I just copied my code :). here is the code that getting a error response.
String url = "MYLINK.com";
try {
RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getContext(), "Successful send pending data", Toast.LENGTH_SHORT).show();
String qu = ("update tickets set is_send = '1' where ticket_tick_no = '" + ticket_tick_no_delayed + "'");
sqldb.execSQL(qu);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "Error Response here", Toast.LENGTH_SHORT).show();
Log.e("------", String.valueOf(error.networkResponse.statusCode));
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("control_no", trip_no_delayed);
params.put("trip_no", ticket_control_no_delayed);
params.put("ticket_no", ticket_tick_no_delayed);
params.put("ticket_datetime", ticket_datetime_delayed);
params.put("ticket_kmfrom", ticket_kmfrom_delayed);
params.put("ticket_kmto", ticket_kmto_delayed);
params.put("ticket_placefrom", ticket_placefrom_delayed);
params.put("ticket_placeto", ticket_placeto_delayed);
params.put("amount", ticket_amount_delayed);
params.put("discount", ticket_discount_delayed);
params.put("trans_type", transaction_type_delayed);
params.put("passenger_type", passenger_type_delayed);
params.put("lat", ticket_lat_delayed);
params.put("long", ticket_long_delayed);
params.put("device_serial", device_serial_delayed);
return params;
}
};
queue.add(postRequest);
} catch (Exception e) {
e.printStackTrace();
}
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!
I need to post parameters to my server and it seems volley ignoring my parameters and give me null values
here is my code:
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("from", textfrom_btn);
params.put("to", textto_btn);
params.put("seat", seat);
Log.e(TAG, "Posting params: " + params.toString());
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
the response always give empty array and server sent message to me that my $_POST["from"] and so on are null
I pass the value from another activity to this activity, and here how I got the value...
first I declare String:
String textfrom, textto, seat
then get value from another activity via intent
Intent extras = getIntent();
if (extras.hasExtra("page")) {
String value = extras.getStringExtra("page");
if(value.equals("search")) {
textfrom_btn = extras.getStringExtra("from");
textto_btn = extras.getStringExtra("to");
seat = extras.getStringExtra("seat");
}
}
and volley StringRequest code after that...