HttpUrlConnection模拟ajax请求

最近遇到一个问题,有请各位大虾帮个忙,解答一下,问题如下:
对方系统提供了一个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);
    }

1个回答

你写get请求,又写con.setRequestProperty("Content-Type", "application/json");肯定不对了,而且你请求的内容是什么?没有请求内容吗?
没有请求内容你写 con.setRequestProperty("Content-Type", "application/json")干什么?

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问