简体   繁体   English

Java连接到Http使用哪种方法?

[英]Java connecting to Http which method to use?

I have been looking around at different ways to connect to URLs and there seem to be a few. 我一直在寻找连接到URL的不同方式,似乎有一些。

My requirements are to do POST and GET queries on a URL and retrieve the result. 我的要求是对URL进行POST和GET查询并检索结果。

I have seen 我见过

URL class
DefaultHttpClient class
HttpClient - apache commons

which method is best? 哪种方法最好?

My rule of thumb and recommendation: Don't introduce dependencies and 3rd party libraries if it's fairly easy to get away without. 我的经验法则和建议: 如果没有依赖,那么不要引入依赖项和第三方库。

In this case I would say, if you need efficiency such as multiple requests per established connection session handling or cookie support etc, go for HTTPClient . 在这种情况下,我会说,如果您需要效率,例如每个已建立的连接会话处理或cookie支持等多个请求,请转到HTTPClient

If you only need to perform an HTTP get, this will suffice: 如果您只需要执行HTTP get,这就足够了:

Getting Text from a URL 从URL获取文本

try {
    // Create a URL for the desired page
    URL url = new URL("http://hostname:80/index.html");

    // Read all the text returned by the server
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String str;
    while ((str = in.readLine()) != null) {
        // str is one line of text; readLine() strips the newline character(s)
    }
    in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}

Sending a POST Request Using a URL 使用URL发送POST请求

try {
    // Construct data
    String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
    data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

    // Send data
    URL url = new URL("http://hostname:80/cgi");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        // Process line...
    }
    wr.close();
    rd.close();
} catch (Exception e) {
}

Both methods work great. 这两种方法都很有效。 (I've even done manual gets/posts with cookies.) (我甚至用cookies完成了手动获取/发布。)

HTTPClient is the way to go if your needs go past trivial URL connection (eg proxy authentication such as NTLM). 如果您的需求超过简单的URL连接(例如NTLM等代理身份验证), HTTPClient就是您的选择。 There are at least a comparison here between standard HTTP client functionality between libraries provided by the JRE, Apache HTTP Client and others. 至少有一个比较标准的HTTP客户端功能之间由JRE,Apache的HTTP客户端和其他方提供的库之间。

If you are using JDK versions earlier to (including 1.4) and have a fairly large data in your post requests, like large file uploads, the default HTTPURLConnection that comes with the JRE is bound to go Out of memory at some point since it buffers the entire data before posting. 如果你之前使用的是JDK版本(包括1.4),并且在你的帖子请求中有相当大的数据,比如大文件上传,那么JRE附带的默认HTTPURLConnection必然会在某些时候出现内存不足,因为它会缓冲发布前的全部数据。 Additionally it does not support some advanced HTTP headers like chunked encoding, etc. 此外,它不支持某些高级HTTP标头,如分块编码等。

So I'd recommend it only if your request are trivial and you are not posting large data as aioobe did. 因此,只有当您的请求微不足道并且您没有像aioobe那样发布大数据时,我才会推荐它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM