为什么收到尝试从主机url加载数据的JSON异常? [英] Why am I receiving a JSON exception trying to load data from host url?

查看:120
本文介绍了为什么收到尝试从主机url加载数据的JSON异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直收到JSON异常.数据将不会加载.

I keep receiving a JSON exception. Data will not load.

PHP代码:

mysql_connect("somedbuser.byethost13.com","user", "pass") or die(mysql_error());

mysql_select_db("some_database");

$id = $_GET["id"];

$sql=mysql_query("select * from brewery_data where id between ($id+1) and ($id+2)");

while($row=mysql_fetch_assoc($sql))
$output[]=$row;

header('Content-Type:Application/json');

echo(json_encode($output));

mysql_close();
?>


public class BrowseBrewery extends MainActivity {

    private AutoCompleteTextView actvBreweryName;
    private AutoCompleteTextView actvBreweryState;
    private RecyclerView recyclerView;
    private LinearLayoutManager linearLayoutManager;
    private CustomAdapter adapter;
    private List<BreweryData> brewery_data_list;
    String[] breweryNames;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.browse_brewery);

        actvBreweryName = (AutoCompleteTextView) findViewById(R.id.actv_brewery_name);
        actvBreweryState = (AutoCompleteTextView) findViewById(R.id.actv_state);
        cbAdditives = (CheckBox) findViewById(R.id.cb_additives);
        recyclerView = (RecyclerView) findViewById(R.id.brewery_recycler_view);

        brewery_data_list = new ArrayList<>();
        load_data_from_server(0);

        linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);

        adapter = new CustomAdapter(this, brewery_data_list);
        recyclerView.setAdapter(adapter);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (linearLayoutManager.findLastCompletelyVisibleItemPosition() == brewery_data_list.size()-1) {
                    load_data_from_server(brewery_data_list.get(brewery_data_list.size()-1).getId());
                }
            }
        });

        for (int i = 0; i < brewery_data_list.size(); i++) {
            breweryNames[i] = brewery_data_list.get(i).getName();
        }

        ArrayAdapter<String> stateAdapter = new ArrayAdapter<>
                (this, android.R.layout.select_dialog_item, states);
        actvBreweryState.setThreshold(1);
        actvBreweryState.setAdapter(stateAdapter);
    }

    private void load_data_from_server(final int id) {
        AsyncTask<Integer,Void,Void> task = new AsyncTask<Integer, Void, Void>() {

            @Override
            protected Void doInBackground(Integer... integers) {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url("http://thebeerguru.byethost13.com/conn_all.php?id="+id).build();
                try {
                    Response response = client.newCall(request).execute();

                    JSONArray array = new JSONArray(response.body().string());

                    for (int i=0; i<array.length(); i++) {
                        JSONObject object = array.getJSONObject(i);

                        BreweryData data = new BreweryData(
                                object.getInt("id"),
                                object.getString("name"),
                                object.getString("image_link"),
                                object.getString("city"),
                                object.getString("state"),
                                object.getString("phone"),
                                object.getString("website"),
                                object.getString("year_established"),
                                object.getInt("rating"),
                                object.getString("featured"));

                        brewery_data_list.add(data);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    System.out.println("End of Content");
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                adapter.notifyDataSetChanged();
            }
        };
        task.execute(id);
    }
}


JSON数据:


JSON DATA:

[{
    "id": "1",
    "name": "57 Brew Pub & Bistro",
    "image_link": "https:\/\/static.wixstatic.com\/media\/d39f67_ffb7b66c09694eea85479d7a478b64a7~mv2.png\/v1\/fill\/w_278,h_209,al_c,usm_0.66_1.00_0.01\/d39f67_ffb7b66c09694eea85479d7a478b64a7~mv2.png",
    "city": "Greenville",
    "state": "MI",
    "phone": "(616) 712-6226",
    "website": "57brewpub.com",
    "year_established": "N.A.",
    "rating": "0",
    "featured": "true"
}]

推荐答案

问题是,我正在使用的Web主机(拜耳主机)实现了一个简单的名为testcookie-nginx-module的安全反机器人模块,用于缓解L7 DDoS攻击.

The problem is that the web host that I am utilizing (Byet Host) implements a simple security antibots module named testcookie-nginx-module for L7 DDoS attack mitigation.

https://kyprizel.github.io/testcookie-nginx-module/

testcookie-nginx模块进行两步验证:

The testcookie-nginx-module makes a 2-step validation:

1)第一次执行HTTP请求时,模块将返回JavaScript,而不是我们期望的JSON.该脚本在客户端(通常是Web浏览器)上执行,并生成包含AES密钥的验证cookie.

1) The first time that a HTTP request is done, the module returns a javascript instead of the JSON we are expecting. This script is executed on the client (tipically a web browser) and generates a validation cookie containing an AES key.

2)脚本将验证cookie添加到文档中,并将其重定向到我们实际要访问的url. testcookie-nginx-module验证cookie AES密钥,并让请求命中将用我们要访问的JSON数据响应的URL. 在以下HTTP请求上,客户端将存储cookie,并将其跳过步骤1添加到请求中.

2) The script adds the validation cookie to the document and redirects it to the url we actually want to access. The testcookie-nginx-module validates the cookie AES key and lets the request hit the url that will respond with the JSON data we want to access. On the following HTTP requests the client will have stored the cookie and will add it to the request skipping the step 1.

我们只需要向HTTP请求添加一个cookie,即可通过testcookie-nginx-module.

We just need to add a cookie to the HTTP request to pass the testcookie-nginx-module.

这些链接应有助于优化代码,并为以后的开发人员解决同一问题提供帮助:

These links should help optimize the code and aid future developers with the same issue:

ByetHost服务器传递html值检查您的浏览器" JSON字符串

将cookie添加到客户端请求OkHttp

:-)

简单地调用.addHeader对我有用.

Simply calling .addHeader worked for me.

        @Override
        protected Void doInBackground(Integer... integers) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("http://thebeerguru.byethost13.com/conn_all.php?id="+id)
                    .addHeader("Cookie", "__test=THE_CONTENT_OF_MY_COOKIE; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/")
                    .build();

            try {
                Response response = client.newCall(request).execute();

                JSONArray array = new JSONArray(response.body().string());

感谢大家的指教和支持!

Thanks to everyone for their counsel and support!

这篇关于为什么收到尝试从主机url加载数据的JSON异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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