使用java获取403错误

时间:2017-01-04 03:41:06

标签: java

当我通过网址" http://echo.jsontest.com/key/value/one/two"到下面的代码,它返回JSON数据。

但是当我通过" 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);
        }
    }

}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

使用:

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

而不是:

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