JAVA 怎么实现HTTP的POST方式通讯,以及HTTPS方式传递
1个回答
推荐于2016-10-19
展开全部
/**
* 执行post请求并将返回内容转为json格式返回
*/
public static JsonObject doPost(String url, JsonObject message)
throws WeiXinException {
JsonObject jo = null;
PrintWriter out = null;
InputStream in = null;
try {
if (url.startsWith("https")){
//https方式提交需要
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },new java.security.SecureRandom());
URL console = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.connect();
in = conn.getInputStream();
}else{
in = new URL(url).openStream();
}
// 打开和URL之间的连接
URLConnection conn = new URL(url).openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(message.toString());
// flush输出流的缓冲
out.flush();
// POST请求
out.flush();
out.close();
in = conn.getInputStream();
jo = JSON.parse(getContext(in));
doExeption(jo);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.flush();
out.close();
}
if (in != null ){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return jo;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询