为什么我无法获取json数据?

时间:2017-07-11 09:19:20

标签: android

我使用post man测试url(post),看起来很好。 API:update frame in matplotlib with live camera preview

但是当我在我的机器人上尝试它时,即使我的响应代码是200,也无法得到消息

我的logcat显示{"Msg":"Request method not accepted","JsonData":null,"ErrorCode":"0099"}

我不明白,我之前使用代码来获取json数据。

有人可以告诉我我错过了哪一步,我将不胜感激。

这是我的get json数据函数:

private String getRoute(String url) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        int responseCode = connection.getResponseCode();
        StringBuilder jsonIn = new StringBuilder();
        // responseCode show 200
        Log.d("responseCode:",responseCode+"");
        if (responseCode == 200) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                jsonIn.append(line);
            }
        } else {
            Log.d(TAG, responseCode + "responseCode");
        }
        connection.disconnect();
        // I can't get the json data it shows Request method not accepted
        Log.d(TAG, jsonIn + "jsonIn");
        return jsonIn.toString();

    }

3 个答案:

答案 0 :(得分:2)

默认情况下,HttpURLConnection正在发送GET请求 您的链接运行正常。
尝试添加
$file = $_FILES["img"]["name"];

Reference

答案 1 :(得分:1)

服务器本身的响应为JsonData为null,您应该在服务器端检查。

答案 2 :(得分:1)

您好,您的链接正在运行发布请求

private String getRoute(String url) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        int responseCode = connection.getResponseCode();
        connection.setRequestMethod("POST");


        StringBuilder jsonIn = new StringBuilder();
        // responseCode show 200
        Log.d("responseCode:",responseCode+"");
        if (responseCode == 200) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                jsonIn.append(line);
            }
        } else {
            Log.d(TAG, responseCode + "responseCode");
        }
        connection.disconnect();
        // I can't get the json data it shows Request method not accepted
        Log.d(TAG, jsonIn + "jsonIn");
        return jsonIn.toString();

    }

我希望它会起作用但在我看来你应该使用Volley或Retrofit而不是HttpURLConnection