此方法在Java中Python的urllib2代码等效于什么?

时间:2019-03-08 20:50:58

标签: java python-2.7 urllib2

我是Python新手,我必须将此代码转换为Java。有人可以帮忙吗?

    def fetch_url(self, url, origin=None):
        cj = cookielib.LWPCookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        if origin:
            opener.addheaders = [('Origin', origin)]
        urllib2.install_opener(opener)
        req = urllib2.Request(url)
        handle = urllib2.urlopen(req)
        page = handle.read()
        return page, handle, cj

到目前为止,我有类似的方法,但是对于相同的URL输出不匹配。

public static String fetchUrl(String url) {
    try {
        URL u = new URL(url);
        return fetch(u);

    } catch (IOException e) {
        return e.getMessage();
    }
}

private static String fetch(URL url) throws IOException {
    StringBuilder content = new StringBuilder();
    try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()))) {
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
    }
    return content.toString();
}

0 个答案:

没有答案