最近遇到一个问题,有请各位大虾帮个忙,解答一下,问题如下:
对方系统提供了一个api,我通过ajax请求json数据类型能请求到,但是通过httpUrlConnection就call不到结果,并且已经设置了Content-Encoding和Content-Type,最后readline读出来始终是空,求解决方案,是不是漏设了什么属性?
原始http请求头信息如下:
Cache-Control
no-cache
Connection
keep-alive
Content-Encoding
gzip
Content-Length
858
Content-Type
application/json;charset=UTF-8
Date
Tue, 16 Aug 2016 07:18:45 GMT
Expires
Wed, 31 Dec 1969 23:59:59 GMT
Pragma
No-cache
Server
nginx/1.10.1
access-control-allow-head...
Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With
access-control-allow-orig...
*
renderer
webkit
viewport
width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0 user-scalable=no
原始头信息
Accept
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding
gzip, deflate
Accept-Language
zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3
Connection
keep-alive
Host
210.73.192.83
Upgrade-Insecure-Requests
1
User-Agent
Mozilla/5.0 (Windows NT 10.0; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0
java代码如下:
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Encoding", "gzip");
con.setRequestProperty("Content-Type", "application/json");
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
Map<String, List<String>> header = con.getHeaderFields();
for (Map.Entry<String, List<String>> entry : header.entrySet()) {
String key = entry.getKey() != null ? entry.getKey() + ":" : "";
System.out.println(key + entry.getValue());
}
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
你写get请求,又写con.setRequestProperty("Content-Type", "application/json");肯定不对了,而且你请求的内容是什么?没有请求内容吗?
没有请求内容你写 con.setRequestProperty("Content-Type", "application/json")干什么?