为什么我尝试从主机URL加载数据时收到JSON异常?

时间:2017-03-29 18:38:00

标签: java php android json

我一直收到JSON异常。数据无法加载。

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 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"
}]

1 个答案:

答案 0 :(得分:0)

问题是我正在使用的Web主机(Byet Host)为L7 DDoS攻击缓解实现了一个名为testcookie-nginx-module的简单安全抗议模块。

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

testcookie-nginx-module进行了两步验证:

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

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

我们只需要在HTTP请求中添加一个cookie来传递testcookie-nginx-module。

这些链接应该有助于优化代码并帮助未来的开发人员解决同样的问题:

ByetHost server passing html values "Checking your browser" with JSON String

Add cookie to client request OkHttp

: - )

简单地调用.addHeader为我工作。

        @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());

感谢大家的建议和支持!