Use java.net.HttpURLConnection/HttpClient 访问web service ( HTTP/HTTPS)

本文介绍如何使用Java通过HTTP和HTTPS发送请求并获取响应内容的方法,包括利用HttpURLConnection和HttpClient进行GET与POST请求的具体实现,特别关注了SSL证书的信任配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

提交request soap message xml到服务器,得到response xml

使用的第三方包
commons-httpclient-3.1.jar
commons-codec-1.3.jar
activation.jar

// use HttpURLConnection
	public static String getResponseContent(String url) throws Exception {
		boolean isSSL = url.toUpperCase().indexOf("HTTPS://") > -1;
		if (isSSL)
			setTrustSSLContent();
		HttpURLConnection conn = null;
		InputStream in = null;
		try {
			URL target = new URL(url);
			conn = (HttpURLConnection) target.openConnection();
			conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
			in = conn.getInputStream();
			String ret = null;
			ret = getContentFromResponse(in);
			in.close();
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				in.close();
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
		return "";
	}

	// use HttpURLConnection
	public static String getResponseContentWithPost(String url,
			String requestFile) throws Exception {
		boolean isSSL = url.toUpperCase().indexOf("HTTPS://") > -1;
		if (isSSL)
			setTrustSSLContent();
		HttpURLConnection conn = null;
		InputStream in = null;
		try {
			URL target = new URL(url);
			conn = (HttpURLConnection) target.openConnection();
			String request = readRequestFile(requestFile);
			conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");

			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("POST");
			conn.getOutputStream().write(request.getBytes());

			in = conn.getInputStream();
			String ret = null;
			ret = getContentFromResponse(in);
			in.close();
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				in.close();
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
		return "";
	}

	// use HttpClient
	public static String getResponseContent(String destination,
			String requestFile, String portNumber) throws Exception {
		String response = null;
		if (destination.toUpperCase().indexOf("HTTPS://") > -1) {
			Protocol myhttps = new Protocol("https", new MySSlSocketFactory(),
					Integer.valueOf(portNumber));
			Protocol.registerProtocol("https", myhttps);
		}

		HttpClient httpclient = new HttpClient();
		PostMethod httpget = new PostMethod(destination);
		httpget.setRequestBody(readRequestFile(requestFile));

		try {
			httpclient.executeMethod(httpget);
			System.out.println(httpget.getStatusLine());

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					httpget.getResponseBodyAsStream()));
			StringBuffer sb = new StringBuffer();
			String tmpstr;
			while (true) {
				tmpstr = reader.readLine();
				if (tmpstr != null) {
					sb.append(tmpstr);
				} else {
					break;
				}
			}
			response = sb.toString();

		} catch (Exception e) {
			throw e;
		} finally {
			httpget.releaseConnection();
		}
		// System.out.println("response=" + response);
		return response;
	}

	private static String getContentFromResponse(InputStream in)
			throws Exception {
		byte[] data = new byte[1];
		BufferedInputStream br = new BufferedInputStream(in);
		StringBuilder sb = new StringBuilder();
		while (br.read(data) != -1) {
			sb.append(new String(data));
		}
		return sb.toString();
	}

	public static String readRequestFile(String fName) throws Exception {
		StringBuffer request = new StringBuffer();
		// read request
		InputStreamReader reqIsr = new InputStreamReader(ConnectionUtils.class
				.getClassLoader().getResourceAsStream(fName));
		BufferedReader reqReader = new BufferedReader(reqIsr);
		String reqLine = null;
		while ((reqLine = reqReader.readLine()) != null) {
			request.append(reqLine);
		}
		if (reqReader != null)
			reqReader.close();
		if (reqIsr != null)
			reqIsr.close();
		return request.toString();
	}

	public static void setTrustSSLContent() {
		TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			}

			public void checkClientTrusted(
					java.security.cert.X509Certificate[] certs, String authType) {
			}

			public void checkServerTrusted(
					java.security.cert.X509Certificate[] certs, String authType) {
			}
		} };
		try {
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, trustAllCerts, new java.security.SecureRandom());
			HttpsURLConnection
					.setDefaultSSLSocketFactory(sc.getSocketFactory());
		} catch (Exception e) {
		}
	}


值得注意的是SSL,也就是HTTPS

这里我们使客户端信任服务器的证书,否则我门必须

使用 -Djavax.net.ssl.trustStore=./key.jks 增加trustStore在java运行的时刻

或增加*.jks到 C:\ibmjdk15\jre\lib\security\cacerts


in workshop, there is proxy server. It only open for http, break socket

in case set System.setProperty("java.net.useSystemProxies","true")

httpclient will be blocked by proxyserver server, but java.net.HttpURLConnection can go.

I mean httpclient uses socket, but not http connection




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值