0

我正在使用 GSON 解析 JSON 数据。这是我的代码 -

public class TestProg {

private static final String storeURL = "https://abcd"; //Haven't given the URL here completely

public static void main(String[] args) throws Exception {
    String getData = getDataFromURL(storeURL);      
    Gson gson = new Gson();
    Test rs = (Test) gson.fromJson(getData.toString(), Test.class);

    List<TestB> testData = rs.getContent();
    for(TestB retStr:testData)
    {
        System.out.println(retStr.getTitle());
        System.out.println(retStr.getOwner());

    }

}

public static String getDataFromURL(String url) throws Exception {
    String dataFromURL = readUrl(url);
    return dataFromURL;
}

public static String readUrl(String inputURL) throws IOException {
        URL url = null;
        BufferedReader br = null;
        StringBuilder sb = null;
        HttpURLConnection conn = null;
        try {
            url = new URL(inputURL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            System.out.println("Failed : HTTP error code :" + conn.getResponseCode());
        }

        br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        sb = new StringBuilder();
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }

        return sb.toString();
    } catch (MalformedURLException e) {
        System.out.print("Exception occured while reading data from the URL "+ e.getMessage()); 
        return null;
    } finally {
        if (br != null)
            br.close();
        conn.disconnect();
    }

}
}

运行代码时出现以下错误 -

Exception in thread "main" com.google.gson.JsonSyntaxException: java.net.MalformedURLException: no protocol: www.abc.com
    at com.google.gson.Gson.fromJson(Gson.java:818)
    at com.google.gson.Gson.fromJson(Gson.java:768)
    at com.google.gson.Gson.fromJson(Gson.java:717)
    at com.google.gson.Gson.fromJson(Gson.java:689)

我不能在这里包含测试类,因为它有一些敏感数据。

4

1 回答 1

0

只需在您的 readUrl(String inputURL) 方法中进行一个小编辑:

    try {
        //Edit starts
        String finalUrl;
        if(!(url.startsWith("http://"))&&!(url.startsWith("https://")))
          {
            finalUrl = "http://"+url;
          }
        //Edit Ends
        url = new URL(finalURL);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

这样,每次发送请求之前,您的 url 都会被修改,它是格式错误的。

于 2013-07-20T08:27:19.597 回答