kobe810911 2016-08-16 06:47 采纳率: 0%
浏览 1499

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条回答 默认 最新

  • a917390823 2016-08-16 08:05
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘