【发布时间】:2018-01-30 21:11:03
【问题描述】:
我正在尝试向服务器发送 get 请求(发送 get 请求进行测试,实际上我需要向同一台服务器发送 post 请求。如果 get 有效,post 将有效)
到服务器的链接是 https://bits-bosm.org/2017/registrations/signup/
问题是当我使用 okHttp 发送请求时,我收到一个失败响应,说握手失败。
这是我使用 okHttp(在 kotlin 中)发送请求的代码
val request = Request.Builder()
.url("https://bits-bosm.org/2017/registrations/signup/")
.build()
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call?, e: IOException?) {
val mMessage = e?.message?.toString()
Log.w("failure Response", mMessage)
}
override fun onResponse(call: Call?, response: Response?) {
val mMessage = response?.body()?.string()
Log.e("Message", mMessage)
}
})
但如果我使用 HttpUrlConnection 将 get 请求发送到同一台服务器,我会得到响应。
这是相同的代码(java)
private static final String USER_AGENT = "Mozilla/5.0";
private static final String GET_URL = "https://bits-bosm.org/2017/registrations/signup/";
static void sendGET() throws IOException {
URL obj = new URL(GET_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
Log.e("Result", response.toString());
} else {
System.out.println("GET request not worked");
}
}
根据我在互联网上的搜索以及我可以推断的内容,问题是该站点是使用自我证书签名的,而 okHttp 不允许它们。我什至尝试使用我在 Internet 上找到的代码 sn-ps,它不检查证书(自定义 SSLSocketFactory)和其他一些解决方案,但它们都不起作用。我现在也不关心安全性,我只想让它工作。但我无法访问后端,也无法更改/删除 ssl 安全性。
怎样才能让它发挥作用?有什么我想念的吗?
【问题讨论】:
标签: android ssl httpurlconnection okhttp