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
Related
When posting a JSONObject to my webservices, I always get the following error:
I/System.out: Error com.android.volley.ParseError: org.json.JSONException: Value Hat of type java.lang.String cannot be converted to JSONObject.message
Always the VolleyError is displayed.
Json looks like this: {"channel1":255,"channel2":255,"channel3":0}
Code to generate JSON:
data class DMX(
var channel1: Int = 0,
var channel2: Int = 0,
var channel3: Int = 0,
)
val DMXValues = DMX(255, 255, 0)
val j = Gson().toJson(DMXValues)
val json = JSONObject(j)
My Webservice processes this one fine, with no errors.
But what's the "Value Hat"?? Didn't find anything on Google...
My code:
val jsonRequest = JsonObjectRequest(Request.Method.POST, url, json, { response ->
Toast.makeText(applicationContext, response.toString(), Toast.LENGTH_SHORT).show()
},
{error: VolleyError ->
println("Error $error.message")
Toast.makeText(applicationContext, "Didn't work!", Toast.LENGTH_SHORT).show()
})
Can you post the exact json you used to get this error, basically your json string has a error(syntax error - in the source string or a duplicated key) in being converted into a JSONObject.
Sample kotlin verion of String request with post body,
val stringRequest: StringRequest = object : StringRequest(httpMethod, url, Response.Listener { response ->
// on response implementation
}, Response.ErrorListener { error ->
//on error implementation
}) {
#Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
return httpHeaders ?: java.util.HashMap()
}
#Throws(AuthFailureError::class)
override fun getBody(): ByteArray {
// return your body here
return 'you body'
}
}
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
I'm facing with error for below code
may someone help me
I'm trying to register by this code to an app
registration with VOLLEY and KOTLIN issue , can somebody say me what is issue I'm getting followed error :
I am adding this for more details to can post my question
W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:111)
`override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
loading = findViewById<ProgressBar>(R.id.loading)
name = findViewById<EditText>(R.id.name)
email = findViewById<EditText>(R.id.email)
password = findViewById<EditText>(R.id.password)
c_password = findViewById<EditText>(R.id.password)
btn_regist = findViewById<Button>(R.id.btn_regist)
btn_regist.setOnClickListener() { v -> regist() }
}
private fun regist(){
loading.visibility = View.VISIBLE
btn_regist.visibility = View.GONE
val name:String = this.name.text.trim().toString()
val email:String = this.email.text.trim().toString()
val password:String = this.password.text.trim().toString()
val stringRequest = object : StringRequest(com.android.volley.Request.Method.POST, URL_REGIST,
com.android.volley.Response.Listener<String>() { response ->
try {
val jsonObject = JSONObject(response)
val success : String = jsonObject.getString("success")
if (success.equals("1")){
Toast.makeText(this, "Register Success ! Eyyvalll !", Toast.LENGTH_SHORT).show()
}
}
catch (e: JSONException){
e.printStackTrace()
Toast.makeText(this, "Register Error ! goh !!!! :/" + e.toString() , Toast.LENGTH_SHORT).show()
loading.visibility = View.GONE
btn_regist.visibility = View.VISIBLE
}
}, com.android.volley.Response.ErrorListener {
error -> error.printStackTrace()
Toast.makeText(this, "Register Error ! SHIT :/" + error.toString() , Toast.LENGTH_SHORT).show()
loading.visibility = View.GONE
btn_regist.visibility = View.VISIBLE
}) {
// #Throws(AuthFailureError::class)
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params["name"] = name
params["email"] = email
params["password"] = password
return params
}
}
val requestQueue = Volley.newRequestQueue(this)
requestQueue.add(stringRequest)
}`
I thing this error because response result is not a valid json format
com.android.volley.Response.Listener<String>() { response ->
try {
//at this point,you can debug result with console log your response
//because if response have a php error then json format not valid
Log.d("RESPONSE"," $response")
val jsonObject = JSONObject(response)
//at this you can check if json has have key name success
if (jsonObject.has("success")){
val success : String = jsonObject.getString("success")
if (success.equals("1")){
Toast.makeText(this, "Register Success ! Eyyvalll !", Toast.LENGTH_SHORT).show()
}
}
}
......
hope this help
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'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)