JSON是显示错误403尝试从Android中数据库获取数据 [英] JSON is showing error 403 while trying to fetch data from database in android

查看:390
本文介绍了JSON是显示错误403尝试从Android中数据库获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我作出有关网上购物的Andr​​oid应用程序。

I am making an android application regarding online shopping.

我能够正确获取数据,并与我的android应用到今天插入数据库中的数据。 (从去年15天,应用程序完美的工作)
今天,当我开始它崩溃,所以我在eclipse检查,我发现,当我试图让HTTP请求到数据库中,它显示访问被拒绝。

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.

我不明白发生了什么事所有的突然..我还没有改变任何我的code,因为4天,再加上此错误显示在所有尝试连接我的SQL数据库的页面。

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..

还有一件事,当我尝试打开我的PHP文件浏览器,那么它显示了JSON字符串完美,因为我想,这意味着数据库被访问,那么它为什么没有在Android平台

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

我的code是如下。

MainActiity.java

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

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

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

For viewing the php output: 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

请帮助..

推荐答案

从拍摄提示<一个href=\"https://developer.appcelerator.com/question/147633/httpclient-returns-403-error-from-my-app-only\"相对=nofollow>这个帖子,我想你可能需要设置用户代理头在你的JSON请求。尝试在 JSONFunction.makeHtt prequest添加一行()调用的execute()像以前一样:

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

或者在打电话前行 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"));

(注意:此用户代理字符串只是其中的一个,我从我的浏览器拉你大概可以使用一个从任何现代浏览器)

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

这会使你的REST服务相信请求是从Web浏览器来了。我怀疑这就是可能会造成403,即你的Web服务器不知道什么样的代理人的要求的来源。至于为什么它只是停止了工作,也许在这里你的PHP服务运行最近,使其不会接受,用户代理未声明的请求更新服务器。

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.

这篇关于JSON是显示错误403尝试从Android中数据库获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆