Jsoup在使用Google Maps API时返回400错误

3
我正在做一个项目,需要在谷歌地图上找到一些商店的坐标。我已经有每家商店的地址了。
我已经尝试了一下Google Geocoding APIs,我认为这正是我所需的:我的代码只需要连接到DBMS,检索item_id和地址,生成一个有效的geocoding API URL并处理它将获取的JSON数据。
我不知道为什么,但我生成的URL在我的浏览器(Chrome 23&latest Safari,OS X)中可以工作,但在Jsoup中无法工作。我已经查看了Chrome页面的源代码,它看起来是完全有效的HTML。那么Jsoup错在哪里呢?
代码片段(可运行,会给您与我得到的相同的异常):
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class RandomClass {
     public static void main(String args[]) {
     Document doc = null;
     try {
        String url = "http://maps.googleapis.com/maps/api/geocode/json?address=0+164+W+75th+St,+New%20York,+NY+10024&sensor=false";

        String ua = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17";
        doc = Jsoup.connect(url).timeout(60 * 1000).userAgent(ua).get();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

抛出
org.jsoup.UnsupportedMimeTypeException: Unhandled content type. Must be text/*, application/xml, or application/xhtml+xml. Mimetype=application/json; charset=UTF-8, URL=http://maps.googleapis.com/maps/api/geocode/json?address=164+W+75th+St,+New%20York,+NY+10024&sensor=false
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:436)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:393)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:159)
at org.jsoup.helper.HttpConnection.get(HttpConnection.java:148)
at asdru.RandomClass.main(RandomClass.java:16)

你需要设置 Content-Type。类似这样的代码 Jsoup.connect(url).header("Content-Type","application/xml") - Srinivas
1个回答

7

试试这个

Jsoup.connect(url).ignoreContentType(true).execute().body();

或者

Jsoup.connect(url).ignoreContentType(true).timeout(60 * 1000).userAgent(ua).get();

1
我刚刚跟随TheWhiteRabbit并成为了Neo。 - Y.Kaan Yılmaz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接