在尝试从android中的数据库获取数据时,JSON显示错误403

I am making an android application regarding online shopping.

I was properly able to fetch data and to insert data in the database with my android application till today. (From last 15 days, the app working perfectly) Today when i started it was crashing, so i checked in eclipse and i found that while i am trying to make the http request to the database, it is showing access denied.

I dont understand what happened all of the sudden.. i havent change any of my code since 4 days, plus this error is showing on all the pages that tries connecting my sql database..

One more thing, when i try to open my php file in browser, then it showing the json string perfectly as i want, that means that database is being access, then why it is not working in android

My code is as follow.

MainActiity.java

package com.example.fashionapp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends Activity 
{
    SessionManager s;
    Context mycontext;
    ImageButton banner,cat1,cat2,cat3,cat4;
    JSONObject jsonobject;
    JSONArray jsonarray;
    ArrayList<HashMap<String, String>> arraylist;
    MainViewAdapter adapter;
    GridView gridmain;
    private String URL_FEED = "http://realroom.byethost24.com/fashionapp/category.php";

    static String CATEGORY_NAME = "cat_name";
    static String PRODUCT_IMAGE = "cat_image";

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        banner = (ImageButton) findViewById(R.id.banner);
        gridmain = (GridView) findViewById(R.id.gridmain);

        Intent intent = new Intent(this, MessageService.class);
        startService(intent);

        TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        String temp = telephonyManager.getDeviceId();
        Log.e("imei", temp);
        Toast.makeText(MainActivity.this, temp,Toast.LENGTH_SHORT).show();

        mycontext=this;
        s = new SessionManager(mycontext);

        banner.setOnClickListener(new Button.OnClickListener() 
        {
            @Override
            public void onClick(View v) 
            {
                // TODO Auto-generated method stub
                Intent i = new Intent(MainActivity.this,Category.class);
                i.putExtra("cat", "1");
                startActivity(i);
            } 
        });

        if(isOnline())
        {
            new DownloadJSON().execute();
        }
    }

    public boolean isOnline() 
    {
         ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
         NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
         if (networkInfo != null && networkInfo.isConnected()) 
         {
             return true;
         } 
         else 
         {
            return false;
         }

    }

    private class DownloadJSON extends AsyncTask<Void, Void, Void> 
    {
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) 
        {
            List<NameValuePair> para = new ArrayList<NameValuePair>();
            arraylist = new ArrayList<HashMap<String, String>>();
            jsonobject = JSONfunctions.makeHttpRequest(URL_FEED, "POST", para);
            Log.e("json",jsonobject.toString());
            try 
            {
                jsonarray = jsonobject.getJSONArray("categories");
                for (int i = 0; i < jsonarray.length(); i++) 
                {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put("cat_name", jsonobject.getString("category_name"));
                    map.put("cat_image", "http://realroom.byethost24.com/fashionapp/admin/fun/data/" + jsonobject.getString("category_img"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } 
            catch (JSONException e)
            {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) 
        {
            gridmain = (GridView) findViewById(R.id.gridmain);
            adapter = new MainViewAdapter(MainActivity.this, arraylist);
            gridmain.setAdapter(adapter);
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        super.onCreateOptionsMenu(menu);
        MenuInflater blowup = getMenuInflater();
        blowup.inflate(R.menu.menuwithsearch, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        Intent i;
        switch(item.getItemId())
        {
        case R.id.action_search:
            break;

        case R.id.currency:
            i = new Intent(this, Currency.class);
            startActivity(i);
            break;

        case R.id.checkout:
            i = new Intent(this, CartActivity.class);
            startActivity(i);
            break;

        case R.id.notifications:
            i = new Intent(this, Notifications.class);
            startActivity(i);
            break;

        case R.id.wish:
            i = new Intent(this, WishActivity.class);
            startActivity(i);
            break;

        case R.id.profile:
           i = new Intent(this,CartActivity.class);
           startActivity(i);
           break;

        case R.id.myorders:
            i = new Intent(this, MyOrders.class);
            startActivity(i);
            break;

        case R.id.logout:
            s.logoutUser();
            i = new Intent(this,LoginActivity.class);
                // Closing all the Activities
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                // Add new Flag to start new Activity
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
            finish();
            break;

        case R.id.settings:

               break;
        }
        return false;
    }
}

JSONFunction.java

package com.example.fashionapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONfunctions
{

     static InputStream is = null;
     static String result = "";
     static JSONObject jArray = null;
    public static JSONObject getJSONfromURL(String url) 
    {
        // Download JSON data from URL
        try 
        {
            Log.e("log_tag", "getjsonfromurl0");
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            Log.e("log_tag", "gethsonfromurl");
        } 
        catch (Exception e) 
        {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // Convert response to string
        try 
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) 
            {
                sb.append(line + "
");
            }
            is.close();
            result = sb.toString();
            Log.e("log_tag", "getjsonfromurl2");
        } 
        catch (Exception e) 
        {
            Log.e("log_tag", "Error converting result " + e.toString());
        }
        try 
        {
            jArray = new JSONObject(result);
        } 
        catch (JSONException e)
        {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
        return jArray;
    }

    public static JSONObject makeHttpRequest(String loginUrl, String post, List<NameValuePair> para)
    {
        try 
        {
            if(post == "POST")
            {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(loginUrl);
                httpPost.setEntity(new UrlEncodedFormEntity(para));
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
                Log.e("log_tag", "post");
            }
            else if(post == "GET")
            {
                HttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(para, "utf-8");
                loginUrl += "?" + paramString;
                HttpGet httpGet = new HttpGet(loginUrl);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        catch (ClientProtocolException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        try 
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
            StringBuilder sb = new StringBuilder();
            Log.e("log_tag", "1");
            String line = null;
            if (is != null) 
            {
                while ((line = reader.readLine()) != null) 
                {
                    Log.e("line",line);
                    sb.append(line + "
");
                }
                is.close();
                result = sb.toString();
                Log.e("log_tag", result);
            }
        }
        catch (Exception e)
        {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        try
        {
            Log.e("log_tag", "posttry2");
            jArray = new JSONObject(result);
            Log.e("log_tag", "posttry3");
        }
        catch (JSONException e)
        {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        return jArray;
    }   
}

category.php

<?php
include('config.php');
date_default_timezone_set("Asia/Calcutta");

$result1 = mysqli_query($con,"SELECT category_name,category_img FROM categorytable");
$response = array();
$posts = array();
while($row=mysqli_fetch_array($result1))
{
    $category_name =$row["category_name"];
    $category_img =$row["category_img"];
    $posts[] = array('category_name'=>$category_name, 'category_img'=> $category_img);

}
$response['categories'] = $posts;
print(json_encode($response));

?>

For viewing the php output: http://realroom.byethost24.com/fashionapp/category.php

Log-output

06-28 00:30:48.180: E/imei(650): 000000000000000
06-28 00:30:48.210: E/json(650): on
06-28 00:30:48.210: E/json(650): online
06-28 00:30:48.242: E/json(650): onli
06-28 00:30:48.661: E/json(650): online
06-28 00:30:48.870: D/gralloc_goldfish(650): Emulator without GPU emulation detected.
06-28 00:30:51.500: E/log_tag(650): post
06-28 00:30:51.531: E/log_tag(650): 1
06-28 00:30:51.542: E/line(650): 403 Access denied
06-28 00:30:51.551: E/log_tag(650): 403 Access denied
06-28 00:30:51.551: E/log_tag(650): posttry2
06-28 00:30:51.571: E/JSON Parser(650): Error parsing data org.json.JSONException: Value 403 of type java.lang.Integer cannot be converted to JSONObject
06-28 00:30:51.571: E/json(650): online
06-28 00:30:51.581: W/dalvikvm(650): threadid=11: thread exiting with uncaught exception (group=0x409961f8)
06-28 00:30:51.631: E/AndroidRuntime(650): FATAL EXCEPTION: AsyncTask #1
06-28 00:30:51.631: E/AndroidRuntime(650): java.lang.RuntimeException: An error occured while executing doInBackground()
06-28 00:30:51.631: E/AndroidRuntime(650):  at android.os.AsyncTask$3.done(AsyncTask.java:278)
06-28 00:30:51.631: E/AndroidRuntime(650):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
06-28 00:30:51.631: E/AndroidRuntime(650):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-28 00:30:51.631: E/AndroidRuntime(650):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
06-28 00:30:51.631: E/AndroidRuntime(650):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-28 00:30:51.631: E/AndroidRuntime(650):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
06-28 00:30:51.631: E/AndroidRuntime(650):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
06-28 00:30:51.631: E/AndroidRuntime(650):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
06-28 00:30:51.631: E/AndroidRuntime(650):  at java.lang.Thread.run(Thread.java:856)
06-28 00:30:51.631: E/AndroidRuntime(650): Caused by: java.lang.NullPointerException
06-28 00:30:51.631: E/AndroidRuntime(650):  at com.example.fashionapp.MainActivity$DownloadJSON.doInBackground(MainActivity.java:229)
06-28 00:30:51.631: E/AndroidRuntime(650):  at com.example.fashionapp.MainActivity$DownloadJSON.doInBackground(MainActivity.java:1)
06-28 00:30:51.631: E/AndroidRuntime(650):  at android.os.AsyncTask$2.call(AsyncTask.java:264)
06-28 00:30:51.631: E/AndroidRuntime(650):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-28 00:30:51.631: E/AndroidRuntime(650):  ... 5 more

Please help..

doukang7501
doukang7501 它的第三方..问题解决了,我没有包括http标头,我的服务器升级,使其必须添加标头,否则它拒绝访问。
大约 5 年之前 回复
doukao8851
doukao8851 拒绝403访问是由服务器端生成的。也许在服务器配置上发生了一些变化,导致无法从程序中获取信息而不是从浏览器中获取信息?您是控制服务器端还是第三方?
大约 5 年之前 回复
doushe8577
doushe8577 它可能与CSRF保护有关吗?看这篇文章:stackoverflow.com/questions/24927731/...
大约 5 年之前 回复
dongtan1845
dongtan1845 在没有任何评论的情况下嘀咕这个问题......:(
大约 5 年之前 回复

1个回答



这篇文章,我想你可能需要在你的JSON请求中设置 User-Agent </ code>标题。 在调用 execute()</ code>之前尝试在 JSONFunction.makeHttpRequest()</ code>中添加一行,如:</ p>

  httpPost.setHeader  (“User-Agent”,“Mozilla / 5.0(Macintosh; Intel Mac OS X 10_9_5)AppleWebKit / 537.36(KHTML,类似Gecko)Chrome / 43.0.2357.81 Safari / 537.36”); 
</ code> </ pre>

或者,在调用 setEntity()</ code>之前的行上,您可以执行以下操作:</ p>

  para.add(new NameValuePair  (“User-Agent”,“Mozilla / 5.0(Macintosh; Intel Mac OS X 10_9_5)AppleWebKit / 537.36(KHTML,类似Gecko)Chrome / 43.0.2357.81 Safari / 537.36”)); 
</ code> </ pre >

(注意:此用户代理字符串只是我从浏览器中提取的字符串。您可以使用任何现代浏览器中的字符串。)</ p>

这将使 您的REST服务认为该请求来自Web浏览器。 我怀疑这可能是导致403的原因,即您的Web服务器不知道请求来自哪种代理。 至于它为什么停止工作,也许最近更新了运行PHP服务的服务器,以便它不接受未声明用户代理的请求。</ p>
</ div>

展开原文

原文

Taking a hint from this post, I think you may need to set the User-Agent header in your JSON request. Try adding a line in JSONFunction.makeHttpRequest() before the call to execute() like:

httpPost.setHeader("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36");

or, on the line before calling setEntity() you could do something like:

para.add(new NameValuePair("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36"));

(Note: this user-agent string is just one I pulled from my browser. You can probably use one from any modern browser.)

This will make your REST service believe that the request is coming from a web browser. I suspect that is what may be causing the 403, i.e. that your web server doesn't know what kind of agent the request is coming from. As for why it just stopped working, perhaps the server where your PHP service is running was updated recently so that it won't accept requests where the user-agent is not declared.

dssj88098
dssj88098 接得好! 固定它。 我不太习惯使用Java而习惯于php / javascript,其中单/双引号可以互换。 :)很高兴它有效。
大约 5 年之前 回复
duangangmo0583
duangangmo0583 非常感谢..救了我.. !! 它工作得很完美..只需一个简单的修正,它将采用双引号而不是单引号。
大约 5 年之前 回复
dox19458
dox19458 那是我需要的完美答案.. !!
大约 5 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问