Volley's StringRequest() - android

As per my knowledge server can response in either XML or JSON format only ,is it true? if it is then how Volley's StringRequest() works?

XML and JSON are formatted Strings. A http request will always return a String. If you are designing the requesting system you should know the format that is expected within that String (the body of the response in particular), and it is for you to decode it.

val stringRequest = object : StringRequest(
Request.Method.POST, Config."Url",
Response.Listener<String> { response ->
try {
val obj = JSONObject(response)
if (!obj.getBoolean("error")) {
val userssListArray = obj.getJSONArray("arrayanme")
for (i in 0 until userssListArray.length()) {
var usersObj = userssListArray.getJSONObject(i)
}
} else {
if (obj.getString("message") == "Your login expired please re login") {
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
finish()
}
}
} catch (e: JSONException) {
e.printStackTrace()
}
},
Response.ErrorListener {
Toast.makeText(this, "Network Error Try Again...", Toast.LENGTH_LONG).show()
}) {
#Throws(AuthFailureError::class)
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
return params
}
}
stringRequest.retryPolicy = DefaultRetryPolicy(
15000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)
//adding request to queue
VolleySingleton.instance?.addToRequestQueue(stringRequest)
this is how volley string request works

Related

Unexpected response code 403 (But work fine in browser)

Im trying to get the json data from below URL
https://newsapi.org/v2/everything?q=tesla&from=2021-05-07&sortBy=publishedAt&apiKey=c9e4ed47388d413c8af23fc46a330f8e
But when I run the app it shows
31029-31125 E/Volley: [228776] NetworkUtility.shouldRetryException: Unexpected response code 403 for https://newsapi.org/v2/everything?q=tesla&from=2021-02-23&sortBy=publishedAt&apiK 20ey=c9e4ed47388d413c8af23fc46a330f8e
31029-31125 E/Volley: [228776] NetworkUtility.shouldRetryException: Unexpected response code 403 for https://newsapi.org/v2/everything?q=tesla&from=2021-02-23&sortBy=publishedAt&apiK 20ey=c9e4ed47388d413c8af23fc46a330f8e
But when I enter the URL in chrome browser it shows the json data normally but I got getting the same thing in my app
here is my code in kotlin
fun getNews(context: Context){
var queue: RequestQueue = Volley.newRequestQueue(context)
val url = "https://newsapi.org/v2/everything?q=tesla&from=2021-05-07&sortBy=publishedAt&apiKey=c9e4ed47388d413c8af23fc46a330f8e"
val request = JsonObjectRequest(
Request.Method.GET, url, null,
{ response ->
var list: MutableList<newModel> = mutableListOf<newModel>()
try {
var rootArray: JSONArray = response.getJSONArray("articles")
for(i in 0 until response.length()){
var dataObject: JSONObject = rootArray.get(i) as JSONObject
list.add(newModel(dataObject.getString("urlToImage") , dataObject.getString("title") , dataObject.getString("description") , dataObject.getString("url")))
}
} catch (e: Exception) {
Toast.makeText(
context,
"error while parsing the jsonObject/array",
Toast.LENGTH_LONG
).show()
}
callBack.gotTheNewsData(list)
}) { error ->
Toast.makeText(context, "Error in responce", Toast.LENGTH_SHORT).show()
}
queue.add(request)
}
I was facing the same error and I solved it by passing a header "Mozilla/5.0" to the request.
This can be done in this way on your code.
fun getNews(context: Context){
var queue: RequestQueue = Volley.newRequestQueue(context)
val url = "Your URL here"
val request = object: JsonObjectRequest(
Request.Method.GET, url, null,
{ response ->
var list: MutableList<newModel> = mutableListOf<newModel>()
try {
var rootArray: JSONArray = response.getJSONArray("articles")
for(i in 0 until response.length()){
var dataObject: JSONObject = rootArray.get(i) as JSONObject
list.add(newModel(dataObject.getString("urlToImage") , dataObject.getString("title") , dataObject.getString("description") , dataObject.getString("url")))
}
} catch (e: Exception) {
Toast.makeText(
context,
"error while parsing the jsonObject/array",
Toast.LENGTH_LONG
).show()
}
callBack.gotTheNewsData(list)
}) { error ->
Toast.makeText(context, "Error in responce", Toast.LENGTH_SHORT).show()
}
// overriding function to add Headers.
{
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers["User-Agent"]="Mozilla/5.0"
return headers
}
}
queue.add(request)
}
It is important to use the object keyword before the construction of the request in order to be able to override the getHeaders() method.
This answer helped me in adding a custom header in Volley request with kotlin.
Override header ["User-Agent"]="Mozilla/5.0"
Or You can use this NewsApi which dont require apikey
https://github.com/SauravKanchan/NewsAPI

returning the value of REST Api response to the calling function

I request your help in solving this pesky problem. I am trying to return the value of 'response' returned by the REST API call, to the calling program. I get null string. Here is the code for your reference. In this code, I want the value of the variable 'response' returned to the caller in onCreate, ie 'restApiResponse' variable.
Thank you very much.
-Vittal
PS: I am a newbie to Kotlin/Android programming.
class OpeningActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_opening)
var restApiResponse = getAPIResponse() // <<<< restApiResponse is empty string
val submitButton = findViewById<Button>(R.id.submitBtn)
submitButton.setOnClickListener() {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
}
fun getAPIResponse() : String {
val myUrl = "YOUR REST API CALL URL"
var jsonObject = JSONObject();
val queue = Volley.newRequestQueue(this);
cpyResponse = StringBuilder();
val stringRequest = object: StringRequest(Request.Method.GET, myUrl,
Response.Listener<String> { response ->
Log.d("A", "VK: Response is: " + response.substring(0, 500))
cpyResponse.append(response.toString())
// .. cpyResponse now has the content of response.
},
Response.ErrorListener { })
{
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers.put("X-API-KEY", "r0IS395C2D8ITjSKV05F610yPXsDQZjllmprr");
return headers
}
}
queue.add(stringRequest)
Log.d("A", "VK: Response is: " + response) // <<<<-- value of response is gone.. it is an empty string!!!!!! :(
return cpyResponse.toString() // <<< --- cpyResource is also empty string
}

JSON object post volley request can't send , shows volley failure message

I can send JSON object request to post data on the server using volley but can't work properly. It always shows a volley failure error. I tried it many times but. I can't know why it happens Kindly share with me the preferable answer Kindly.
private fun login() {
val params = JSONObject()
params.put("email",login_email.text.toString())
params.put("password",login_password.text.toString())
val url = "http://192.168.10.100/fitness_app/api/v1/login"
val queue = Volley.newRequestQueue(this)
val request = object : JsonObjectRequest(
Request.Method.POST,url,params,
Response.Listener<JSONObject> { response ->
val code = response.getInt("code")
if(code==101)
{
Toast.makeText(this,"Successfully login", Toast.LENGTH_SHORT).show()
}
else if(code==102)
{
Toast.makeText(this,"Unauthorized user", Toast.LENGTH_SHORT).show()
}
else if(code==103)
{
Toast.makeText(this,"Email does not exist", Toast.LENGTH_SHORT).show()
}
}, Response.ErrorListener {
Toast.makeText(this,"Something went wrong. Please try later.Volley Error", Toast.LENGTH_SHORT).show()
}
)
{
}
queue.add(request)
}
The code given above is exactly write . I just forget to make httptrafficlibrary true in manifest that is false by default.

I need help for post to my api. What should I do?

I'm creating a login for my application.
I am currently stuck in posting problems to my API
This is my API that which is made to support login.
{
success: false,
message: "Please provide complete and accurate information.",
data: [ ]
}
fun loginUrlSuccess(urlApi : String) {
Log.d("login", urlApi)
authSignin_cgi = gson.fromJson(urlApi, DtoProfile::class.java)
loginsSuccess = authSignin_cgi.success
val queue = Volley.newRequestQueue(context)
val stringReq = object : StringRequest(Request.Method.POST,urlApi,Response.Listener<String>{ response ->
Log.w("response",response)
Toast.makeText(context,"Loging success..",Toast.LENGTH_SHORT).show()
if (loginsSuccess){
Toast.makeText(context,authSignin_cgi.message,Toast.LENGTH_LONG).show()
} else {
Toast.makeText(context,authSignin_cgi.message,Toast.LENGTH_LONG).show()
}
},Response.ErrorListener { error ->
Log.w("error", error.toString())
Toast.makeText(context, "error..$error",Toast.LENGTH_SHORT).show()
}){
override fun getParams(): MutableMap<String, String> {
val param = HashMap<String, String>()
val userEmail = textEmail.text.toString().trim()
val userPassword = textPassword.text.toString().trim()
param["useremail"] = userEmail
param["userpassword"] = userPassword
return param
}
}
queue.add(stringReq)
}
I get an error from the Logcat screen.
So what do I have to do?
04-04 15:31:43.614 8365-8699/com.example.atimeonlin5 E/Volley: [700] NetworkDispatcher.processRequest: Unhandled exception java.lang.RuntimeException: Bad URL {"success":false,"message":"โปรดระบุข้อมูลให้ถูกต้องครบถ้วน","data":[]}
java.lang.RuntimeException: Bad URL {"success":false,"message":"โปรดระบุข้อมูลให้ถูกต้องครบถ้วน","data":[]}
All right , you should try to construct an Url object instead of type String !
You should use an url (like "http://www.google.com"), not a random string. Your urlApi is not url.
Example from doc:
val textView = findViewById<TextView>(R.id.text)
// ...
// Instantiate the RequestQueue.
val queue = Volley.newRequestQueue(this)
val url = "http://www.google.com"
// Request a string response from the provided URL.
val stringRequest = StringRequest(Request.Method.GET, url,
Response.Listener<String> { response ->
// Display the first 500 characters of the response string.
textView.text = "Response is: ${response.substring(0, 500)}"
},
Response.ErrorListener { textView.text = "That didn't work!" })
// Add the request to the RequestQueue.
queue.add(stringRequest)

Request working on Insomnia but not Android?

I have the following request on Insomnia:
Which is working fine!
But, if I try to do this on Android with volley I get a "ServerError":
fun createRequest() {
val params = JSONObject()
params.put("device_key", Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID))
params.put("edition_date", "2018-02-12 00:00:00")
params.put("publication", 1)
val headers = hashMapOf<String, String>()
headers["Authorization"] = "My Token"
headers["Content-Type"] = "application/x-www-form-urlencoded"
getPDF(this, params, headers)
}
fun getPDF(activity: Activity, params: JSONObject, headers: HashMap<String, String>) {
val request = object : JsonObjectRequest(Request.Method.POST, "My URL", params,
Response.Listener {
print("asd")
},
Response.ErrorListener {
it.printStackTrace()
}
) {
override fun getHeaders(): Map<String, String> { return headers } }
request.retryPolicy = DefaultRetryPolicy(0, DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT)
Volley.newRequestQueue(activity).add(request)
}
I'm only getting a "ServerError" with a code 500.
What could I be doing wrong in Android? Am I not settings the header correctly? Or could be the params?
In Insomnia you are making a request and the body is a form, while in Android you are trying to send a JSON. Make sure your body consists of key-value pairs and not a JSON object.

Categories

Resources