gpt4 book ai didi

java - 尝试从 Android 数据库中获取数据时 JSON 显示错误 403

转载 作者:行者123 更新时间:2023-11-29 12:08:24 25 4
gpt4 key购买 nike

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

直到今天,我都能够使用我的 Android 应用程序正确获取数据并将数据插入数据库。 (从过去 15 天开始,该应用程序运行良好)今天,当我启动时,它崩溃了,所以我检查了 eclipse,发现当我尝试向数据库发出 http 请求时,它显示访问被拒绝。

我不明白突然发生了什么......我已经 4 天没有更改任何代码了,而且这个错误显示在所有尝试连接我的 sql 数据库的页面上......

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

我的代码如下。

MainActivity.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;
}
}

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

请帮忙..

最佳答案

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

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 服务相信请求来自网络浏览器。我怀疑这可能是导致 403 的原因,即您的 Web 服务器不知道请求来自哪种代理。至于为什么它停止工作,可能是运行 PHP 服务的服务器最近更新了,因此它不会接受未声明用户代理的请求。

关于java - 尝试从 Android 数据库中获取数据时 JSON 显示错误 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31092236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com