2017-01-04 47 views
0

當我將URL「http://echo.jsontest.com/key/value/one/two」傳遞給下面的代碼時,它返回JSON數據。使用java獲取403錯誤

但是,當我通過「http://jsonplaceholder.typicode.com/comments?postId=1」而不是,我得到403禁止錯誤。

我不確定發生了什麼事。有什麼建議?

package automation_Demo_First; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.Reader; 
import java.net.URL; 
import java.nio.charset.Charset; 

import org.testng.annotations.Test; 


public class JsonReader{ 

    //http://jsonplaceholder.typicode.com/comments?postId=1 
    public String url ="http://echo.jsontest.com/key/value/one/two"; 
    @Test 
    public void testJson() throws IOException{ 

     String data = getDataByJavaIO(url); 
     System.out.println(data); 
    } 



    public String getDataByJavaIO(String url) throws IOException{ 
     InputStream inputstream = null; 
     BufferedReader bufferreader = null; 

     try{ 
      inputstream = new URL(url).openStream(); 
      bufferreader = new BufferedReader(new InputStreamReader(inputstream, Charset.forName("UTF-8"))); 
      return readData(bufferreader); 

     }catch(IOException e){ 
      throw e; 

     } 
     finally{ 

      closeResource(inputstream); 
      closeResource(bufferreader); 
     } 


    } 




    public String readData(Reader reader) throws IOException{ 

     StringBuilder stringbuilder = new StringBuilder(); 
     int cp; 
     while((cp=reader.read())!=-1){ 
      stringbuilder.append((char)cp); 
     } 
     return stringbuilder.toString(); 


    } 

    public void closeResource(AutoCloseable closable){ 

     try{ 
      if(closable!=null){ 
       closable.close(); 
       System.out.println("\n" +closable.getClass().getName() + "closed ..."); 
      } 
     } 
     catch(Exception e){ 

      e.printStackTrace(System.err); 
     } 
    } 

}

+0

[我得到403 repsonse]的可能的複製(https://github.com/typicode/jsonplaceholder/issues/34) – shmosel

回答

0

在你try塊,

try { 
    inputstream = new URL(url).openStream(); 
    bufferreader = new BufferedReader(new InputStreamReader(inputstream, Charset.forName("UTF-8"))); 
    return readData(bufferreader); 
} 

將其更改爲

try { 
    HttpURLConnection httpCon = (HttpURLConnection) new URL(url).openConnection(); 
    httpCon.addRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36"); 
    inputstream = httpCon.getInputStream(); 
    bufferreader = new BufferedReader(new InputStreamReader(inputstream, Charset.forName("UTF-8"))); 
    return readData(bufferreader); 
} 

來源:https://stackoverflow.com/a/18889991/3903483

0

用途:

URLConnection hc = new URL(url).openConnection(); 
hc.setRequestProperty("User-Agent", ""); 
inputstream = hc.getInputStream(); 

相反的:

inputstream = new URL(url).openStream();