2016-04-03 113 views
0

我使用此代碼獲取Json,但它返回FileNotFoundException。在browset中它工作。我不明白爲什麼它不工作在Java ... 我嘗試使用HttpsUrlConnection,但結果沒有改變。Google書籍filenotfound java

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 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) 
+0

您可以進行適當的更改,如鏈接中所述:http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/ – AbhishekAsh

+0

測試2 - 發送Http POST請求 線程「main」中的異常java.io.FileNotFoundException:https://selfsolve.apple.com/wcResults.do \t at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native –

回答

0

谷歌圖書只能使用GET請求