i have a web service in this url : https://server_IP:9443/api/v1/ssids.json/
but it needs login in this page : https://server_IP:9443/login
when i make the request with the credentials in the headers , i got "Unexpected response code 401"
so how can i authenticate and get the json.
here is my code :
val request = object : StringRequest(Request.Method.GET, url, Response.Listener { response ->
if (response != null) {
Log.e("Your Array Response", response)
} else {
Log.e("Your Array Response", "Data Null")
}
}, Response.ErrorListener { error -> Log.e("error is ", "" + error) }) {
override fun getHeaders() : Map<String, String> {
val username ="admin"
val password = "admin"
val auth = "$username:$password"
var data = auth.toByteArray()
var base64 = Base64.encodeToString(data, Base64.NO_WRAP)
var headers = HashMap<String, String>()
headers.put("Authorization",base64)
headers.put("accept-language","EN")
headers.put("Content-type","application/json")
headers.put("Accept","application/json")
return headers
}
}
val queue = Volley.newRequestQueue(this)
queue.add(request)
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 need make request with Volley and kotlin my cod is
val stringReq = StringRequest(
Request.Method.GET, url,
Response.Listener<String> { response ->
var strResp = response.toString()
val jsonObj: JSONObject = JSONObject(strResp)
val jsonArray: JSONArray = jsonObj.getJSONArray("curso")
for (i in 0 until jsonArray.length()) {
var jsonInner: JSONObject = jsonArray.getJSONObject(i)
listGeral.add(jsonInner.get("interpret").toString());
listGeral2.add(jsonInner.get("titel").toString());
listGeral3.add(jsonInner.get("id").toString());
}
},
Response.ErrorListener {
})
queue.add(stringReq)
Now I need send 3 parameters for php. How do I put instruction for send parameter?
you can write the below code after Response.ErrorListener
val sr: StringRequest = object : StringRequest(Method.POST, "url",
Response.Listener { response ->
//your response
},
Response.ErrorListener { error ->
//your error
}) {
override fun getParams(): Map<String, String> {
val params: MutableMap<String, String> = HashMap()
params["user"] = "YOUR USERNAME"
params["pass"] = "YOUR PASSWORD"
return params
}
#Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val params: MutableMap<String, String> = HashMap()
params["Content-Type"] = "application/x-www-form-urlencoded"
return params
}
}
queue.add(sr)
I would like to save response code from volley calls to db, but it seems like parseNetworkResponse() is not being called. Any idea why does it behave like this?
All of my calls are GET, some has code 500 and some has code 200 with json response, so I think it should be called.
private fun createCall(url: String, type: Int, data: JSONObject, callback: Int, request: DbRequestEntity) {
val jsonRequest = object : JsonObjectRequest(type, url, data,
Response.Listener { response ->
Log.d(tag, "Response $response")
try {
callback(response, data, callback, request)
} catch (e: Exception) {
request.responseCode = 999
request.responseMessage = e.message
db.requestMoodel().update(request)
Log.d(tag, "API callback error $e ${e.localizedMessage} ${e.stackTrace}")
}
},
Response.ErrorListener { error ->
Log.d(tag, "API error $error")
errorCallback(error, callback)
}
) {
val tag = "JsonObjectRequest"
override fun getHeaders(): Map<String, String> {
val headers = HashMap<String, String>()
headers[ConstantsStorage.API_HEADER_CLIENT_ID] = ConstantsStorage.API_HEADER_CLIENT_ID_VALUE
headers[ConstantsStorage.API_HEADER_CLIENT_CONTENT_TYPE] = ConstantsStorage.API_HEADER_CLIENT_CONTENT_TYPE_VALUE
return headers
}
override fun parseNetworkResponse(response: NetworkResponse): Response<JSONObject> {
Log.d(tag, "Response code = ${response.statusCode}") //not getting this message to Logcat
return super.parseNetworkResponse(response)
}
}
queue.add(jsonRequest)
}
Replace your parseNetworkResponse function with below code
override fun parseNetworkResponse(response: NetworkResponse): Response<JSONObject> {
try {
if (response.data.length == 0) {
byte[] responseData = "{}".getBytes("UTF8");
response = new NetworkResponse(response.statusCode, responseData, response.headers, response.notModified);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return super.parseNetworkResponse(response)
}
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.
1.I'm getting the correct response back and can view it in logcat, but I need to save that response and store it for later. I'm trying to save it in the var token, but when looking in memory token remains empty even after correctly getting the response. Any suggestions would be appreciated.
class Login : AppCompatActivity() {
var token = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
//POST data
log_login.setOnClickListener {
// "http://localhost:1842/token"
var url = "https://elimination.azurewebsites.net/token"
val que = Volley.newRequestQueue(this#Login)
val stringRequest = object : StringRequest(Request.Method.POST, url,
Response.Listener { response -> Toast.makeText(this#Login, response, Toast.LENGTH_LONG).show()
Log.e("Test", response)
//trying to set token to response
token = response},
Response.ErrorListener { error -> Toast.makeText(this#Login, error.toString(), Toast.LENGTH_LONG).show()
Log.e("Wrong", error.toString())}) {
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params.put("grant_type", "password")
params.put("Username", input_email.toString())
params.put("Password", input_password.toString())
return params
}
}
que.add(stringRequest)
val intent = Intent(this, Profile::class.java)
intent.putExtra("token", token) //passing token to profile intent
startActivity(intent)
}
}
}
Try moving the intent initialization to when you receive the correct response:
log_login.setOnClickListener {
// "http://localhost:1842/token"
var url = "https://elimination.azurewebsites.net/token"
val que = Volley.newRequestQueue(this#Login)
val stringRequest = object : StringRequest(Request.Method.POST, url,
Response.Listener { response -> Toast.makeText(this#Login, response, Toast.LENGTH_LONG).show()
Log.e("Test", response)
//trying to set token to response
token = response
val intent = Intent(this, Profile::class.java)
intent.putExtra("token", token)
startActivity(intent)
},
Response.ErrorListener { error -> Toast.makeText(this#Login, error.toString(), Toast.LENGTH_LONG).show()
Log.e("Wrong", error.toString())}) {
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params.put("grant_type", "password")
params.put("Username", input_email.toString())
params.put("Password", input_password.toString())
return params
}
}
que.add(stringRequest)
}
Or calling a method when you receive the result:
log_login.setOnClickListener {
// "http://localhost:1842/token"
var url = "https://elimination.azurewebsites.net/token"
val que = Volley.newRequestQueue(this#Login)
val stringRequest = object : StringRequest(Request.Method.POST, url,
Response.Listener { response -> Toast.makeText(this#Login, response, Toast.LENGTH_LONG).show()
Log.e("Test", response)
//trying to set token to response
token = response
openNextActivity(token);
},
Response.ErrorListener { error -> Toast.makeText(this#Login, error.toString(), Toast.LENGTH_LONG).show()
Log.e("Wrong", error.toString())}) {
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params.put("grant_type", "password")
params.put("Username", input_email.toString())
params.put("Password", input_password.toString())
return params
}
}
que.add(stringRequest)
}
fun openActivity(token: String){
val intent = Intent(this, Profile::class.java)
intent.putExtra("token", token)
startActivity(intent)
}
The important thing is you were trying to execute the intent initialization syncronously, but you receive the token async so you token variable was not filled when the intent was executed.