java调用https接口

cainong1997 cainong1997 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

public static String sendPost(String url, String body, String ak_id, String ak_secret) {

PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
trustAllHttpsCertificates();

URL realUrl = new URL(url);

/*
* http header 参数
*/
String method = "POST";
String accept = "json";
String content_type = "application/json";
String path = realUrl.getFile();

String date = toGMTString(new Date());

// 1.对body做MD5+BASE64加密
String bodyMd5 = MD5Base64(body);
String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date + "\n"+ path;
// 2.计算 HMAC-SHA1
String signature = HMACSha1(stringToSign, ak_secret);
// 3.得到 authorization header
String authHeader = "Dataplus " + ak_id + ":" + signature;

// 打开和URL之间的连接
HttpsURLConnection https = (HttpsURLConnection)realUrl.openConnection();
HostnameVerifier hv=new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName + " vs. "
+ session.getPeerHost());
return true;
}
};
https.setHostnameVerifier(hv);
HttpURLConnection conn= https;

// 设置通用的请求属性

conn.setRequestProperty("accept", accept);
conn.setRequestProperty("content-type", content_type);
conn.setRequestProperty("date", date);
conn.setRequestProperty("Authorization", authHeader);
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(body);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
InputStream is;
int a=conn.getResponseCode();
if ( a== 200) {
is = conn.getInputStream();
} else {
is = conn.getErrorStream();
}
in = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}

这个方法传http接口可以正常访问并且读取返回结果,但是传https接口就报404?请问哪里出了问题啊
...全文

相关推荐

评论 4
收藏 已收藏
分享
返回顶部
cainong1997
Java EE 67,535 成员 225,843 内容