当我将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);
}
}
}
[我得到403 repsonse]的可能的复制(https://github.com/typicode/jsonplaceholder/issues/34) – shmosel