2017-01-04 43 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();