我在Android应用程序中尝试使用HTTPS做了很多。实际上我在这里的工作是想从服务器进行api调用,并希望获得authourisation。
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
DefaultHttpClient client = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
// Set verifier
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
// Example send http request
final String url = "https://(serveraddress).../";
HttpPost httpPost = new HttpPost(url+ zAPIName);
byte[] byteArray = (zUserNameP.trim() + ":" + zPasswordP.trim()).getBytes();
String EncodedString = Base64.encodeBytes(byteArray);
httpPost.setHeader("Authorization", "Basic " + EncodedString);
httpPost.setEntity(zStringEntityL);
HttpResponse aHttpResponseL;
aHttpResponseL = client.execute(httpPost);
BufferedReader aBufferedReaderL = new BufferedReader(new InputStreamReader(
aHttpResponseL.getEntity().getContent()));
StringBuffer aStringBufferL = new StringBuffer("");
String zLineL = "";
String zLineSeparatorL = System.getProperty("line.separator");
while ((zLineL = aBufferedReaderL.readLine()) != null) {
aStringBufferL.append(zLineL + zLineSeparatorL);
}
aBufferedReaderL.close();
zResponserResultL = aStringBufferL.toString();
aResultL.StatusCode = aHttpResponseL.getStatusLine().getStatusCode();
ResposeMessage aMessageL = new ResposeMessage();
Gson gson = new Gson();
aMessageL = gson.fromJson(zResponserResultL, ResposeMessage.class);
aResultL.ResponseString = aMessageL.message;
在上面的代码中如果我正在使用(HTTP)“http://(serveraddress)... /”它的工作正常,但它不适用于(HTTPS)“https://(serveraddress)... / ”。我尝试了我们网站上提供的所有解决方案。但没有得到解决。请帮助我。
答案 0 :(得分:0)
这看起来很复杂......我的解决方案要小得多。我从未在https上尝试过,但我认为这也可以。
只需设置http客户端的凭据:
httpClient = new DefaultHttpClient();
String user = prefs.getString("http_auth_username", "");
String pwd = prefs.getString("http_auth_password", "");
httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pwd));
然后您不必手动设置auth标头。