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

时间:2015-06-27 18:41:33

标签: java php android mysql json

我正在制作一个关于网上购物的Android应用程序。

我能够使用我的Android应用程序直到今天才能获取数据并在数据库中插入数据。 (从最近15天开始,应用程序完美运行) 今天当我开始它崩溃,所以我检查了eclipse,我发现,当我试图向数据库发出http请求时,它显示访问被拒绝。

我不明白突发事件发生了什么..我从4天以来没有更改任何代码,加上这个错误显示在试图连接我的sql数据库的所有页面上..

还有一件事,当我尝试在浏览器中打开我的php文件时,它就像我想要的那样完美地显示json字符串,这意味着数据库正在访问,那么为什么它在android中不起作用

我的代码如下。

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 + "\n");
            }
            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 + "\n");
                }
                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));

?>

用于查看php输出:    http://realroom.byethost24.com/fashionapp/category.php

登入输出

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

请帮助..

1 个答案:

答案 0 :(得分:1)

this post获取提示,我认为您可能需要在JSON请求中设置User-Agent标头。尝试在调用JSONFunction.makeHttpRequest()之前在execute()添加一行,如:

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");

或者,在致电setEntity()之前,您可以执行以下操作:

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"));

(注意:这个用户代理字符串只是我从浏览器中提取的字符串。您可以在任何现代浏览器中使用它。)

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