duanla8800
duanla8800
2015-06-27 18:41
浏览 182

在尝试从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..

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douya1855
    douya1855 2015-06-27 19:17
    已采纳

    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.

    点赞 评论

相关推荐