Android HttpURLConnection 以获取 JSON 与 azurewebsites

Android HttpURLConnection to get a JSON with azurewebsites

我尝试连接到这个 URL:

http://551bba54-0ee0-4-231-b9ee.azurewebsites.net/api/values

使用这个简单的代码:

HttpURLConnection connection = (HttpURLConnection) new URL(http://551bba54-0ee0-4-231-b9ee.azurewebsites.net/api/values).openConnection();
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.connect();
        Response response = new GsonBuilder().create().fromJson(new InputStreamReader(connection.getInputStream()), classOfResult);
        if (response != null)
            return response;
        }
}

响应总是 "null"。不知道为什么。

我也尝试使用:

connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");

没有效果。

如果我在浏览器中打开 URL,这就是响应(正确的 JSON 响应)

[{"Codice":"P1"},{"Codice":"P2"}]

谁能帮帮我?

非常感谢

您可以试试下面的代码:

private void sendGet() throws Exception {

        String url = "http://www.google.com/search?q=mkyong";

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        //add request header
        con.setRequestProperty("User-Agent", USER_AGENT);

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println(response.toString());

    }

来自 http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/