Server returned HTTP response code: 400

前端 未结 5 1478
一个人的身影
一个人的身影 2020-12-10 12:37

I am trying to get an InputStream from a URL. The URL can be a opened from Firefox. It returns a json and I have installed an addon for viewing json in Firefox so I can view

5条回答
  •  生来不讨喜
    2020-12-10 13:10

    I had a similar issue and my url was:

    http://www.itmat.upenn.edu/assets/user-content/documents/ITMAT17. October 10 2017_.pdf
    

    which obviously contained spaces.

    These caused java.io.IOException Server returned HTTP response code: 400 in the following code:

    java.net.URL url = new URL(urlString);  
    java.io.InputStream in = url.openStream();
    

    If you copy the above url and paste in browser, you will realize that browser adds '%20' for the spaces. So I did it manually with the following code and the problem is solved.

    if(urlString.contains(" "))
        urlString = urlString.replace(" ", "%20");
    

    Complete code/answer should be:

    if(urlString.contains(" "))
        urlString = urlString.replace(" ", "%20");
    java.net.URL url = new URL(urlString);  
    java.io.InputStream in = url.openStream();
    

提交回复
热议问题