Server returning 403 for url openStream()

前端 未结 3 1699
故里飘歌
故里飘歌 2021-01-04 22:50
import java.net.URL;
import java.io.*;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Test {
           


        
3条回答
  •  一个人的身影
    2021-01-04 23:25

    This is an old post but if people wanted to know how this works.

    a 403 means acces-denied. There is a work around for this. If you want to able to do this you have to set a user agant parameter to 'fool' the website

    This is how my old method looked like:

    private InputStream read() {
    try {
        return url.openStream();
     } 
    catch (IOException e) {
      String error = e.toString();
      throw new RuntimeException(e);
     }
    }
    

    Changed it to: (And it works for me!)

    private InputStream read() {
    try {
        HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
        httpcon.addRequestProperty("User-Agent", "Mozilla/4.0");
    
      return httpcon.getInputStream();
     } catch (IOException e) {
        String error = e.toString();
      throw new RuntimeException(e);
     }
    }
    

提交回复
热议问题