使用GSON时格式错误的URL异常

时间:2013-07-20 08:17:26

标签: java gson

我正在使用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)

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

1 个答案:

答案 0 :(得分: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");

这样,每次发送请求之前,您的网址都会被修改,它就会格格不入。