java调用https接口

cainong1997 2016-10-21 01:35:35

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?请问哪里出了问题啊
...全文
710 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
tianfang 2016-10-24
  • 打赏
  • 举报
回复
404 就是路径问题 连接百度首页是因为它不支持post方式连接,所以给你个404也说的过去,给500更好
梨花剑君 2016-10-21
  • 打赏
  • 举报
回复
支持楼主一下。
cainong1997 2016-10-21
  • 打赏
  • 举报
回复
引用 1 楼 qq_35441045 的回复:
看不懂,404一般都是路径问题,看看你的url
路径肯定没问题的,我用"https://www.baidu.com"试都会报404,但是用http的就正常,急死了,好几天了
qq_35441045 2016-10-21
  • 打赏
  • 举报
回复
看不懂,404一般都是路径问题,看看你的url

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧