0
這裏請對HTTPS服務器的請求,是我的代碼,以使一個POST請求的HTTP服務器上的servlet擊中一個servlet
private static void post(String endpoint, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v(TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
當我的終點是像HTTP:// myipaddress: MyPort上/它運作良好,但是當我已經改變了它它不工作的HTTPS連接我看了一下HttpsURLConnection太多,但我沒有得到如何實現它那裏,他們寫了這以下代碼:
KeyStore keyStore = ...;
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(keyStore);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
URL url = new URL("https://www.example.com/");
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
InputStream in = urlConnection.getInputStream();
但我不能得到什麼應該在Keystore我只有文件文件,如果我使用Keystore.getInstance(String類型)如何獲取證書的類型。
請幫幫我。
新AllVerifier()不工作 – pyus13
是什麼問題...,我已經使用相同的代碼,沒有issue ... – Shiva
其實我已經將它們定義爲內部類,所以它現在給出了一個錯誤我做了什麼,我已經通過直接使用新的HostnameVerifier和新的X509TrustManager及其工作良好感謝很多重寫了方法。 – pyus13