Server returned HTTP response code: 400

I am trying to get an InputStream from a url. URL can be opened from Firefox. It returns json, and I installed the addon to view json in Firefox, so I can view it there.

So, I tried to get it with Java:

URL url = new URL(urlString);
URLConnection urlConnection = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

But it throws an IOException in urlConnection.getInputStream ().

I also tried:

HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = url.openStream();

But no luck.

Any information is noticeable. Thanks in advance.

+14
source share
4 answers

Thanks to everyone. This is a strange problem, but I finally solved it.

URL I'm requesting

http://api.themoviedb.org/2.1/Movie.search/en/json/api_key/a nightmare on elm street 

" " "%20" . . Java "%20", Bad Request, source.

.

BufferedReader reader = new BufferedReader(new InputStreamReader(((HttpURLConnection) (new URL(urlString)).openConnection()).getInputStream(), Charset.forName("UTF-8")));
+31

, URL :

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

.

, java.io.IOException Server HTTP: 400 :

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

URL- , , " %20" . , .

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

Are you connecting correctly? here is some code that illustrates how to do this. Please note that I am lazy about handling exceptions here, this is not a product quality code.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class URLFetcher {

    public static void main(String[] args) throws Exception {
        URL myURL = new URL("http://www.paulsanwald.com/");
        HttpURLConnection connection = (HttpURLConnection) myURL.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.connect();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder results = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            results.append(line);
        }

        connection.disconnect();
        System.out.println(results.toString());
    }
}
+3
source

encode the parameters in the url as follows:

String messageText = URLEncoder.encode(messageText, "UTF-8");
0
source

All Articles