Java使用HttpURLConnection打开和读取URL

 

本文将展示了多种使用Java来打开URL连接,然后从该连接读取数据的方法,包括如何使用Java URL和URLConnection类教程来打开和读取URL。在此示例中,我将展示如何使用Java HttpURLConnection类打开URL 。如Javadoc所述,此类是URLConnection类的子类,URLConnection类“提供对特定于HTTP的功能的支持”。

Java HttpURLConnection示例

跳入其中……这是一个完整的Java类的源代码,该类演示了如何使用HttpURLConnection该类打开URL,然后从中读取内容。此类还演示了如何使用URLEncoder类的encode方法正确编码URL :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpURLConnection;
import java.net.URL;

public class JavaHttpUrlConnectionReader {
	public static void main(String[] args) {

		String myUrl = "http://localhost:8080/jspwebmon/validate.jsp?username=test&password=test";

		URL url = null;
		BufferedReader reader = null;
		StringBuilder stringBuilder;

		try {
			// create the HttpURLConnection
			url = new URL(myUrl);
			CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));

			HttpURLConnection connection = (HttpURLConnection) url.openConnection();

			// just want to do an HTTP GET here
			connection.setRequestMethod("GET");

			// give it 15 seconds to respond
			connection.setConnectTimeout(15 * 1000);
			connection.setReadTimeout(15 * 1000);

			long startTimerConnect = System.currentTimeMillis();

			connection.connect();
			long stopTimerConnect = System.currentTimeMillis();
			int connectTime = (int) ((int) stopTimerConnect - startTimerConnect);

			// read the output from the server
			long startTimerRead = System.currentTimeMillis();
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			stringBuilder = new StringBuilder();

			String line = null;
			while ((line = reader.readLine()) != null) {
				stringBuilder.append(line + "\n");
			}
			System.out.println(stringBuilder.toString());
			long stopTimerRead = System.currentTimeMillis();
			int readTime = (int) ((int) stopTimerRead - startTimerRead);

			System.out.println("connectTime:" + connectTime);
			System.out.println("readTime:" + readTime);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// close the reader; this can throw an exception too, so
			// wrap it in another try/catch block.
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException ioe) {
					ioe.printStackTrace();
				}
			}
		}
	}
}

 

讨论:Java HttpUrlConnection示例

这是此JavaHttpUrlConnection代码的工作原理的快速概览:

  1. 创建一个新的URL。
  2. 它将打开一个连接,然后将该连接转换为HttpURLConnection。
  3. 它将request方法设置为GET(相对于其他方法,例如POST)。
  4. (可选:setDoOutput告诉对象我们将把输出写入此URL。)
  5. 我将读取超时设置为15秒,然后进行连接。
  6. 我像往常一样使用InputStreamReader和BufferedReader读取数据。
  7. 当我从URL读取输出的每一行时,我将其添加到StringBuilder中,然后在方法返回时将StringBuilder转换为String。

如前所述,该setDoOutput方法是可选的。这是其Javadoc中的简短说明:

URL连接可用于输入和/或输出。如果您打算将URL连接用于输出,请将DoOutput标志设置为true,否则将其设置为false。默认为false。

在此示例中,由于我没有向URL写入任何内容,因此将该设置保留为默认值false。

总而言之,当您知道自己专门处理HTTP连接时,HttpURLConnection该类提供了许多便利的方法和字段,可以使您的编程工作变得更轻松。

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值