Search code examples
javaposthttpsgoogle-books

Google books filenotfound java


I use this code for get Json, but it return FileNotFoundException. In browset it work. I dont understand why it not work in Java... I try use HttpsUrlConnection, but result not change.

   String url = "https://www.googleapis.com/books/v1/volumes";
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("q", "isbn:9785090212779");
    StringBuilder postData = new StringBuilder();
    if (params != null)
        for (Map.Entry<String, String> param : params.entrySet()) {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }
    byte[] postDataBytes = postData.toString().getBytes("UTF-8");

    HttpsURLConnection urlc = (HttpsURLConnection)
            new URL(url).openConnection();
    urlc.setDoOutput(true);
    urlc.setRequestMethod("GET");
    urlc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    urlc.setRequestProperty("charset", "UTF-8");
    urlc.setRequestProperty("Content-Length", Integer.toString(postDataBytes.length));
    DataOutputStream wr;
    wr = new DataOutputStream(urlc.getOutputStream());
    wr.write(postDataBytes);
    wr.flush();
    wr.close();


    urlc.setConnectTimeout(2000);
    DataInputStream is = new DataInputStream(urlc.getInputStream());
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    br.close();
    urlc.disconnect();
    System.out.println(sb.toString());

Exception:

Exception in thread "main" java.io.FileNotFoundException: https://www.googleapis.com/books/v1/volumes
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1836)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at Main.main(Main.java:43)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Solution

  • Google Books use only GET request