【问题标题】:E/Volley: [44820] Network Utility. should Retry Exception: Unexpected response code 403E/Volley:[44820] 网络实用程序。应该重试异常:意外的响应代码 403
【发布时间】:2021-05-31 21:20:13
【问题描述】:

我想从 news Api 获取数据,但我的日志猫显示错误 E/Volley: [44820] NetworkUtility.shouldRetryException: Unexpected response code 403 , 告诉我解决方案

这是一个新闻应用,目的是从newsApi.org获取数据,并将图片标题放到TextViews的recycler view上...... 但是当我在我的 android 设备上运行这个应用程序时,这个应用程序在日志中显示错误并且我的应用程序正在记录

主要活动代码

package com.example.newsfeeds

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    lateinit var mAdapter: NewsListAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val layoutManager = LinearLayoutManager(this)
        recyclerView.layoutManager = layoutManager
        fetchData()
         mAdapter = NewsListAdapter()
        recyclerView.adapter = mAdapter
    }

    private fun fetchData(){
        val url = "https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=cedef5f84e094e23a55e8de8120243ba"

        val newsJsonObjectRequest = JsonObjectRequest(
            Request.Method.GET,
            url,
            null,
            Response.Listener {

                val newsJsonArray = it.getJSONArray("articles")
                val newsArray = ArrayList<News>()
                for(i in 0 until  newsJsonArray.length()){
                    val newsJsonObject = newsJsonArray.getJSONObject(i)
                    val news = News(
                        newsJsonObject.getString("author"),
                        newsJsonObject.getString("title"),
                        newsJsonObject.getString("url"),
                        newsJsonObject.getString("imageToUrl")
                    )
                    Toast.makeText(this,"Entered",Toast.LENGTH_LONG).show()
                    newsArray.add(news)
                }
                mAdapter.update(newsArray)

            },Response.ErrorListener {

            }

        )
        val queue = MySingleton.getInstance(this).requestQueue
        queue.add(newsJsonObjectRequest)

    }
}

适配器代码

package com.example.newsfeeds

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.single_item_look.view.*

class NewsListAdapter() : RecyclerView.Adapter<NewsViewHolder>() {
  private var  items : ArrayList<News> = ArrayList()
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.single_item_look,parent,false)
        return NewsViewHolder(view)
    }

    override fun getItemCount(): Int {
        return items.size
    }

    override fun onBindViewHolder(holder: NewsViewHolder, position: Int) {
        val currentItem = items[position]
        holder.titleView.text = currentItem.title
    }
    fun update(updatedItems : ArrayList<News>){
        items.clear()
        items.addAll(updatedItems)

        notifyDataSetChanged()
    }
}
class NewsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val titleView : TextView = itemView.title

}

MySingletonCode

package com.example.newsfeeds

import android.content.Context
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.ImageLoader
import com.android.volley.toolbox.Volley

class MySingleton constructor(context: Context) {
    companion object {
        @Volatile
        private var INSTANCE: MySingleton? = null
        fun getInstance(context: Context) =
            INSTANCE ?: synchronized(this) {
                INSTANCE ?: MySingleton(context).also {
                    INSTANCE = it
                }
            }
    }

    val requestQueue: RequestQueue by lazy {

        Volley.newRequestQueue(context.applicationContext)
    }
    fun <T> addToRequestQueue(req: Request<T>) {
        requestQueue.add(req)
    }
}

新闻代码

package com.example.newsfeeds

data class News(val author : String ,
                val title : String,
                val url :String,
                val urlToImage : String)

【问题讨论】:

  • 你应该将 newsJsonObject.getString("imageToUrl") 改为 newsJsonObject.getString("urlToImage") 否则应用会崩溃,或者至少使用 Gson 将响应数据转换为新闻对象

标签: android android-studio kotlin


【解决方案1】:

覆盖 getHeaders() 方法并将 Mozilla/5.0 作为 User-Agent 传递 不要忘记将 API-KEY 替换为 URL 中的 API 密钥

    fun fetchData() {
    val queue = Volley.newRequestQueue(this)
    val url = "https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=API-KEY"
    val getRequest: JsonObjectRequest = object : JsonObjectRequest(
        Request.Method.GET,
        url,
        null,
        Response.Listener {
            Log.e("sdsadas","$it")
            val newsJsonArray = it.getJSONArray("articles")
            val newsArray = ArrayList<News>()
            for(i in 0 until  newsJsonArray.length()){
                val newsJsonObject = newsJsonArray.getJSONObject(i)
                val news = News(
                    newsJsonObject.getString("author"),
                    newsJsonObject.getString("title"),
                    newsJsonObject.getString("url"),
                    newsJsonObject.getString("urlToImage")
                )
                Toast.makeText(this,"Entered",Toast.LENGTH_LONG).show()
                newsArray.add(news)
            }
            mAdapter.update(newsArray)
        },
        Response.ErrorListener { error ->

        }
    ) {
        @Throws(AuthFailureError::class)
        override fun getHeaders(): Map<String, String> {
            val params: MutableMap<String, String> = HashMap()
            params["User-Agent"] = "Mozilla/5.0"
            return params
        }
    }
    queue.add(getRequest)
}

【讨论】:

    猜你喜欢
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多