您的位置:首页 > 理论基础 > 计算机网络

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

2012-10-24 14:40 381 查看
提交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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: