https返回400,服务器返回HTTP响应代码:400

"博主在尝试使用Java从URL获取JSON数据时遇到了IOException。问题在于URL中存在空格,浏览器会自动将其转换为"%20",而Java请求时未进行此转换,导致服务器返回BadRequest。解决方法是将URL中的空格替换为"%20",之后成功获取到JSON数据的InputStream。"
摘要由CSDN通过智能技术生成

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 it there.

So I tried to get it from Java by:

URL url = new URL(urlString);

URLConnection urlConnection = url.openConnection();

BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

But it is throwing an IOException in urlConnection.getInputStream().

I also tried:

HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

InputStream inputStream = url.openStream();

But no luck.

Any information is appreciable. Thanks in advance.

解决方案

Thank you everybody. This is a weird problem but at last I solved it.

The URL I am requesting is

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

Now browser replaces the spaces between "a nightmare on elm street" by "%20" internally and parses. That is why the requested server can response by that request. But From Java I didn't replaced that spaces by "%20", so it turns into Bad Request, source.

Now it is working.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值