yash gupta
yash gupta

Reputation: 67

Unexpected response code 403 while fetching data from apis

i want to fetch data from certain api,i don't know where i'm going wrong in my logcat its showing error that unexpected response code 403 this is my Main Activity

public class MainActivity extends AppCompatActivity {
    RequestQueue queue;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    queue=MySingleton.getInstance(this).getmRequestQueue();
    getList();
}
ArrayList getList(){
    JsonObjectRequest jsonObjectRequest =new JsonObjectRequest(Request.Method.GET,
            "https://newsapi.org/v2/top-headlines?country=in&apiKey=e613af58839749aab8f66bba967ab5a8", null
            , new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
                try {

                    String val=response.getString("status");
                    Log.d("json","status : "+val);
                    //i want to see this val in my logcat but its giving an error

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    queue.add(jsonObjectRequest);
    return questionsobjectList;

}

this is my logcat pls help me out to solve this error i'm a begginer

2020-10-28 22:52:41.477 21412-21438/com.e.practice E/gralloc: Arm Module v1.0
2020-10-28 22:52:41.478 21412-21438/com.e.practice E/ion: ioctl c0044901 failed with code -1: Invalid argument
2020-10-28 22:52:41.479 21412-21438/com.e.practice W/gralloc: WARNING: internal format modifier bits not mutually exclusive. AFBC basic bit is always set, so extended AFBC support bits must always be checked.
2020-10-28 22:52:41.523 21412-21412/com.e.practice I/Choreographer: Skipped 1 frames!  The application may be doing too much work on its main thread.
2020-10-28 22:52:41.682 21412-21448/com.e.practice I/System.out: [socket] e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaUtils
2020-10-28 22:52:43.174 21412-21448/com.e.practice E/Volley: [11812] BasicNetwork.performRequest: Unexpected response code 403 for https://newsapi.org/v2/top-headlines?country=in&apiKey=e613af58839749aab8f66bba967ab5a8
2020-10-28 22:52:43.190 21412-21448/com.e.practice I/System.out: [socket] e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaUtils
2020-10-28 22:52:44.553 21412-21448/com.e.practice D/Volley: [11812] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] https://newsapi.org/v2/top-headlines?country=in&apiKey=e613af58839749aab8f66bba967ab5a8 0xc16ea6dd NORMAL 1> [lifetime=3147], [size=12664], [rc=403], [retryCount=1]
2020-10-28 22:52:44.554 21412-21448/com.e.practice E/Volley: [11812] BasicNetwork.performRequest: Unexpected response code 403 for https://newsapi.org/v2/top-headlines?country=in&apiKey=e613af58839749aab8f66bba967ab5a8
2020-10-28 22:58:27.524 21412-21412/com.e.practice D/ColorViewRootUtil: nav gesture mode swipeFromBottom ignore true downY 1021 mScreenHeight 2400 mScreenWidth 1080 mStatusBarHeight 54 globalScale 1.125 nav mode 3 event MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=22.0, y[0]=1021.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=55841499, downTime=55841499, deviceId=3, source=0x1002, displayId=0 } rotation 0
2020-10-28 22:58:27.556 21412-21412/com.e.practice D/ColorViewRootUtil: do not ignore inject event MotionEvent:MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=22.0, y[0]=1021.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=55841499, downTime=55841498, deviceId=3, source=0x1002, displayId=0 }

Upvotes: 1

Views: 5186

Answers (7)

Navneet
Navneet

Reputation: 51

Here you go, Just copy the code and add your api key

 private fun fetchData() {

    val url = "https://newsapi.org/v2/top-headlines?country=us&apiKey=your_api_key"

    val jsonObjectRequest = object :JsonObjectRequest(Request.Method.GET, url, null,

        { response ->
            val newsJsonArray = response.getJSONArray("articles")
            val newsArray = ArrayList<News>()
            for (i in 0 until newsJsonArray.length()) {
                val newsJsonObject = newsJsonArray.getJSONObject(i)
                val news = News(
                    newsJsonObject.getString("title"),
                    newsJsonObject.getString("author"),
                    newsJsonObject.getString("url"),
                    newsJsonObject.getString("urlToImage")
                )
                newsArray.add(news)
            }

            mAdapter.updateNews(newsArray)

        },
        { _ ->

        })

    {
        @Throws(AuthFailureError::class)
        override fun getHeaders(): Map<String, String>? {
            val headers = HashMap<String, String>()
            headers["User-Agent"] = "Mozilla/5.0"
            return headers
        }
    }
   // Access the RequestQueue through your singleton class.
 MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest)
}

Upvotes: 1

Rahul Aggarwal
Rahul Aggarwal

Reputation: 1

This worked for me. Extend the request and put the following lines of code.

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("User-Agent", "Mozilla/5.0");
    return headers;
}

Upvotes: 0

who-aditya-nawandar
who-aditya-nawandar

Reputation: 1242

Anyone stumbling across this in future, this is what worked for me

            objHttpURLConn.setRequestProperty("Accept", ACCEPT_PROPERTY);  // added
            objHttpURLConn.setRequestProperty("User-Agent", USER_AGENT_PROPERTY); // added                
            objHttpURLConn.setRequestMethod("GET");
            objHttpURLConn.connect();

wherever you make the connection (doInBackground, most probably) and........

Here is the definition for the variables:

    private static final String ACCEPT_PROPERTY = "application/geo+json;version=1";
    private static final String USER_AGENT_PROPERTY = "newsapi.org ([email protected])"; //your email id for that site.

before onCreate......

Upvotes: 0

algodextrous
algodextrous

Reputation: 79

Try this header file in java:

@Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            //headers.put("Content-Type", "application/json");
            headers.put("key", "Value");
            return headers;
        }

or in kotlin:

@Throws(AuthFailureError::class)
fun getHeaders(): Map<String, String>? {
    val headers = HashMap<String, String>()
    //headers.put("Content-Type", "application/json");
    headers["key"] = "Value"
    return headers
}

Upvotes: 0

anubhav sharma
anubhav sharma

Reputation: 61

Adding a custom getHeader to the request can help. To do so add object: before construction of the request, and below mentioned getHeader function.

 private fun fetchData() {
    //volly library
    val url = "http://newsapi.org/v2/top-headlines?country=in&apiKey=a13cd2a274a84257ad4b8ce468e0180a"
    //making a request
    val jsonObjectRequest = object: 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("title"),
                    newsJsonObject.getString("author"),
                    newsJsonObject.getString("url"),
                    newsJsonObject.getString("urlToImage")
                )
                newsArray.add(news)
            }

            mAdapter.updateNews(newsArray)
        },
        Response.ErrorListener {
        }

    ) {
        override fun getHeaders(): MutableMap<String, String> {
            val headers = HashMap<String, String>()
            headers["User-Agent"] = "Mozilla/5.0"
            return headers
        }
    }

    MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest)
}

Upvotes: 5

Sohel S9
Sohel S9

Reputation: 246

Same Is I faced. But When I change the library from volley to retrofit its work like a charm.

Upvotes: 0

iamabs2001
iamabs2001

Reputation: 131

Recently Newsapi.org has said that free version of api is only available to localhost, if you want to access free (developer key) then host it in your backend service or make own rest api using that key.

policy screenshot

Upvotes: 5

Related Questions