Java 远程请求 HttpURLConnection 用法详解

1、继承关系

1.1、所有父类继承

  • java.lang.Object
    • java.net.URLConnection
      • java.net.HttpURLConnection

1.2、子类

  • HttpsURLConnection 

2、父类 URLConnection 解析

  • 公共抽象类 URLConnection extends Object抽象类

        URLConnection是表示应用程序和URL之间的通信链接的所有类的超类。这个类的实例可以用来读取和写入URL引用的资源。通常,创建到URL的连接是一个多步骤的过程:

        openConnection() :操纵影响与远程资源连接的参数。

        connect() :与资源互动;查询标题字段和内容。
---------------------------->
步骤:
        连接对象是通过调用URL上的openConnection方法创建的。
        设置参数和常规请求属性被操纵。
        使用connect方法建立到远程对象的实际连接。
        远程对象变为可用。可以访问标题字段和远程对象的内容。

使用以下方法修改设置参数:

        setAllowUserInteraction
        setDoInput
        setDoOutput
        setIfModifiedSince
        setUseCaches

使用以下方法修改常规请求属性:

    调用 setRequestProperty 、 AllowUserInteraction 和 UseCaches 参数的默认值可以使用 setDefaultAllowUserInteraction 和 setDefaultUseCaches 方法来设置。

        上面的每个set方法都有一个相应的get方法来检索参数的值或一般请求属性。适用的具体参数和一般请求属性是协议特定的。

连接到远程对象后,使用以下方法访问标题字段和内容:

  • getContent
  • getHeaderField
  • getInputStream
  • getOutputStream

某些标题字段经常被访问。方法:

  • getContentEncoding
  • getContentLength
  • getContentType
  • getDate
  • getExpiration
  • getLastModifed

        提供方便的访问这些领域。 getContent方法使用getContentType方法来确定远程对象的类型;子类可能会发现覆盖getContentType方法很方便。

        在通常情况下,所有预连接参数和常规请求属性都可以忽略:预连接参数和请求属性默认为合理值。对于这个接口的大多数客户来说,只有两个有趣的方法:getInputStream和getContent,它们通过方便的方法被镜像到URL类中。

 

3、本类 HttpURLConnection 解析

  • 公共抽象类 HttpURLConnection extends URLConnection

        一个支持HTTP特定功能的 URLConnection。详情请参阅规格。


        每个 HttpURLConnection 实例用于发出一个请求,但与HTTP服务器的底层网络连接可能被其他实例透明地共享。在请求后,在 HttpURLConnection 的 InputStream 或 OutputStream 上调用 close() 方法可以释放与此实例关联的网络资源,但对任何共享的持久连接都没有影响。如果此时持久连接处于空闲状态,调用 disconnect() 方法可能会关闭底层套接字。

        HTTP协议处理程序有一些可以通过系统属性访问的设置。这包括代理设置以及其他各种设置。

安全权限

        如果安装了一个安全管理器,并且如果一个方法被调用导致试图打开一个连接,则调用者必须拥有:

  • 将“SocketPermission”连接到目标URL的主机/端口组合
  • 一个允许这个请求的URLPermission。

        如果启用了自动重定向,并且该请求被重定向到另一个目的地,则调用者还必须具有连接到重定向主机/ URL的权限。

4、用法

4.1.创建连接:

     URL url = new URL("http://localhost:8080/TestHttpURLConnectionPro/index.jsp"); 

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

4. 2.设置 Connection 参数:

     

    conn.setRequestMethod( "POST");        // 提交模式

    conn.setRequestProperty( "Content-Type", "application/json;charset=UTF-8" );               //设置请求属性

    conn.setRequestProperty( "User-Agent", "Autoyol_gpsCenter" );

     conn.setConnectTimeout(100000); //连接超时 单位毫秒

     conn.setReadTimeout(100000);    //读取超时 单位毫秒

     conn.setDoOutput( true);         //是否输入参数

     conn.setDoInput( true);        //是否读取参数

     

4.3.连接:

     conn.connect();

4.4.获取写数据流:

     OutputStream outStrm = httpUrlConnection.getOutputStream();

4.5.写数据:

     outStrm.write(bytes); // 输入参数

     outStrm. flush();

     outStrm.close();

4.6.读数据:

     InputStream in = conn.getInputStream();

     byte[] buffer = new byte[521];

     ByteArrayOutputStream baos = new ByteArrayOutputStream();

     for ( int len = 0; (len = in.read(buffer)) > 0;) {

          baos.write(buffer, 0, len);

     }

     String returnValue = new String(baos.toByteArray(), "utf-8" );

     reg= JSON. parseObject(returnValue, ReturnMessage.class );

     baos.flush();

     baos.close();

     in.close();

     conn.disconnect();

5、代码例子

5.1、POST类型方法封装例子:

	/**
	 * 发送http请求:post类型
	 * 
	 * @param url  请求路径
	 * @param data 携带参数(格式:key1=value1&key2=value2)
	 * @param cookie
	 * @return
	 * @throws IOException
	 * @throws KeyManagementException
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchProviderException
	 */
	public Map<String, Object> doPost(String url, String data, String cookie, String contentType)
			throws IOException, KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException {
		Map<String, Object> resultMap = new HashMap<>();

		HttpsURLConnection conn = (HttpsURLConnection) new URL(url.trim()).openConnection();	// 打开连接
		conn.setDoOutput(true);	//设置允许输入
		conn.setDoInput(true);
		conn.setRequestMethod("POST");
		conn.setUseCaches(false);
		conn.setRequestProperty("Charset", "UTF-8");
		if (StringUtils.isNotBlank(cookie)) {
			conn.setRequestProperty("Cookie", cookie);
			resultMap.put("requestCookie", cookie);
		}
		if (StringUtils.isNotBlank(contentType)) {
			conn.setRequestProperty("Content-Type",contentType);
			resultMap.put("requestContentType", contentType);
		}
		conn.connect();

		if (data != null){	//设置参数
			PrintWriter pw = new PrintWriter(conn.getOutputStream());
			pw.write(data);
			pw.flush();
			pw.close();
			resultMap.put("requestData", data);
		}
		StringBuffer resultStr = new StringBuffer();
		int code = conn.getResponseCode();
		resultMap.put("code", code);
		if (200 == code || 201 == code || 204 == code) {
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null;
			while ((line = br.readLine()) != null) {
				resultStr.append(line);
			}
		}
		String setCookie = conn.getHeaderField("Set-Cookie");
		String[] setCookieArr = setCookie.split(";")[0].split("=");
		String sessionid = "";
		for (int i = 0; i < setCookieArr.length; i++) {
			if ("sessionid".equals(setCookieArr[i]) && i + 1 < setCookieArr.length) {
				sessionid = setCookieArr[i + 1];
			}
		}

		resultMap.put("result", resultStr);
		resultMap.put("cookie", setCookie);
		resultMap.put("sessionid", sessionid);

		conn.disconnect();
		return resultMap;
	}

5.2、GET类型方法封装例子:

	/**
	 * 发送http请求:get类型
	 * 
	 * @param url 请求路径
	 * @param cookie
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchProviderException
	 * @throws KeyManagementException
	 * @throws IOException
	 * @throws MalformedURLException
	 */
	public Map<String, Object> doGet(String url, String cookie)
			throws IOException, KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException {
		Map<String, Object> resultMap = new HashMap<>();
		HttpsURLConnection conn = (HttpsURLConnection) new URL(url.trim()).openConnection();	// 打开连接
		if (StringUtils.isNotBlank(cookie)) {
			conn.setRequestProperty("Cookie", cookie);
			resultMap.put("requestCookie", cookie);
		}
		conn.connect();

		StringBuffer resultStr = new StringBuffer();
		int code = conn.getResponseCode();
		resultMap.put("code", code);
		if (200 == code || 201 == code || 204 == code) {
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null;
			while ((line = br.readLine()) != null) {
				resultStr.append(line);
			}
		}
		String setCookie = conn.getHeaderField("Set-Cookie");
		String[] setCookieArr = setCookie.split(";")[0].split("=");
		String sessionid = "";
		for (int i = 0; i < setCookieArr.length; i++) {
			if ("sessionid".equals(setCookieArr[i]) && i + 1 < setCookieArr.length) {
				sessionid = setCookieArr[i + 1];
			}
		}

		resultMap.put("result", resultStr);
		resultMap.put("cookie", setCookie);
		resultMap.put("sessionid", sessionid);

		conn.disconnect();
		return resultMap;
	}

5.3、HTTPS 绕开验证的方法

在类中加入成员变量:

	TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}

		public void checkClientTrusted(X509Certificate[] certs, String authType) {
		}

		public void checkServerTrusted(X509Certificate[] certs, String authType) {
			// don't check
		}
	} };

再在请求的方法里增加几行代码即可,以 POST 类型方法封装为例:

	/**
	 * 发送http请求:post类型
	 * 
	 * @param url  请求路径
	 * @param data 携带参数(格式:key1=value1&key2=value2)
	 * @param cookie
	 * @return
	 * @throws IOException
	 * @throws KeyManagementException
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchProviderException
	 */
	public Map<String, Object> doPost(String url, String data, String cookie, String contentType)
			throws IOException, KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException {
		Map<String, Object> resultMap = new HashMap<>();

		HttpsURLConnection conn = (HttpsURLConnection) new URL(url.trim()).openConnection();	// 打开连接
		SSLContext ctx = SSLContext.getInstance("SSL", "SunJSSE");
		ctx.init(null, trustAllCerts, new java.security.SecureRandom());
		conn.setSSLSocketFactory(ctx.getSocketFactory());
		HostnameVerifier allHostsValid = new HostnameVerifier() {
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		};
		conn.setHostnameVerifier(allHostsValid);	//绕开验证
		conn.setDoOutput(true);	//设置允许输入
		conn.setDoInput(true);
		conn.setRequestMethod("POST");
		conn.setUseCaches(false);
		conn.setRequestProperty("Charset", "UTF-8");
		if (StringUtils.isNotBlank(cookie)) {
			conn.setRequestProperty("Cookie", cookie);
			resultMap.put("requestCookie", cookie);
		}
		if (StringUtils.isNotBlank(contentType)) {
			conn.setRequestProperty("Content-Type",contentType);
			resultMap.put("requestContentType", contentType);
		}
		conn.connect();

		if (data != null){	//设置参数
			PrintWriter pw = new PrintWriter(conn.getOutputStream());
			pw.write(data);
			pw.flush();
			pw.close();
			resultMap.put("requestData", data);
		}
		StringBuffer resultStr = new StringBuffer();
		int code = conn.getResponseCode();
		resultMap.put("code", code);
		if (200 == code || 201 == code || 204 == code) {
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null;
			while ((line = br.readLine()) != null) {
				resultStr.append(line);
			}
		}
		String setCookie = conn.getHeaderField("Set-Cookie");
		String[] setCookieArr = setCookie.split(";")[0].split("=");
		String sessionid = "";
		for (int i = 0; i < setCookieArr.length; i++) {
			if ("sessionid".equals(setCookieArr[i]) && i + 1 < setCookieArr.length) {
				sessionid = setCookieArr[i + 1];
			}
		}

		resultMap.put("result", resultStr);
		resultMap.put("cookie", setCookie);
		resultMap.put("sessionid", sessionid);

		conn.disconnect();
		return resultMap;
	}

 

参考文章:

        http://www.cnblogs.com/beijixingzhiguang/p/4992458.html

        http://elim.iteye.com/blog/1979837

参考资料:

        JDK1.8

转载于:https://my.oschina.net/watsonos/blog/1583399

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用 Java 代码编写 HttpURLConnection 发送 GET 和 POST 请求的示例: 1. 发送 GET 请求 ```java import java.net.*; import java.io.*; public class HttpGet { public static void main(String[] args) { try { URL url = new URL("http://example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 2. 发送 POST 请求 ```java import java.net.*; import java.io.*; public class HttpPost { public static void main(String[] args) { try { URL url = new URL("http://example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setDoOutput(true); String input = "{\"username\":\"test\",\"password\":\"test\"}"; OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 注意,在发送 POST 请求时需要设置 `Content-Type` 和向输出流中写入请求体。如果需要发送其他类型的请求,可以根据需要修改 `setRequestMethod` 和请求头部。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值