java公网部署调用第三方API连接问题报错

来源:互联网 发布:压缩json 编辑:程序博客网 时间:2024/06/07 12:00

问题描述:自己做的开发小项目,用到第三方API,豆瓣,聚合数据都可以.根据isbn码查询书,返回json. 出现在的问题是开发中用HttpClient作为连接。异常是java.lang.IllegalStateException: Failure initializing default SSL context.奇怪的是开发时没异常。部署到公网上才有。

  分析一:想到可能是证书导致的,因为之前对证书不了解。所以想把调用豆瓣的httpsAPI换成http协议的。豆瓣也有就是返回的是xml解析完。试着部署。还是报错。

  分析二:是不是防火墙没拦截了请求。服务器上查看防火墙是关闭的。排除。

解决:找了人看还是没发现代码本身有什么问题。最后找的其他项目中已经正常使用的解决方案。是用的URLConnection。整体按照这个修改了连接.部署。异常消失。正常调用。并返回了正确的结果。

总结:问题只要不放弃解决就一定能解决。过程长短的不同而已。在百度上搜索解决方案怎么都找不到对路子的。写下来算是遇到此问题的人一点帮助吧。

两端代码大致粘一下吧。细节自己修改:

HttpClient代码:

public static String get(String url) {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
String json = "";
try {
HttpResponse res = client.execute(get);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
json = EntityUtils.toString(entity, "UTF-8");
} else {
System.out.println("失败" + res.getStatusLine().getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭连接 ,释放资源
client.getConnectionManager().shutdown();
}
return json;
}

URLConnection代码:

try {
//String urlNameString = "https://api.tianapi.com/social/?key=b358480033319f1e8d5cadc3a59e0505&num=10";

addressname = URLEncoder.encode(addressname, "UTF-8");
String city = URLEncoder.encode("北京", "UTF-8");

String urlNameString = "http://restapi.amap.com/v3/place/text?key=571bdde43751cab4702d2bf7ad54cec6&keywords="+addressname+"&types=&city=" + city+"&children=1&offset=10&page=1&extensions=all";


URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "application/json;charset=utf8");
conn.setRequestProperty("Connection", "Keep-Alive");
//conn.setRequestProperty("apikey", "0a0b165bc779c1d359b613fa3ed978a9");
// 建立实际的连接
conn.connect();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
result = sb.toString();
System.out.println(sb);
ret.setResultModel(result);
ret.setMsg("true");
System.out.println(urlNameString);
} catch (Exception e) {
e.printStackTrace();
ret.setMsg("false");
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
}
}

原创粉丝点击