我一直在到处寻找,但我发现的信息不适用于我的情况。有人可以帮我解决这个问题:我需要使用 Android 应用程序向服务器上的特定 url 发送 POST 请求。目标页面使用 https 加密并受 htaccess 保护。最后一件事:服务器在随机端口(如 14000)上侦听,并且在证书中主机名与主机名的 url 不同。我知道这很有挑战性,但我尝试过的任何方法都没有奏效。目前我尝试这个:
private void process() {
new Thread(new Runnable() {
public void run() {
String httpsURL = "https://login:password@z-cloud.z-wave.me/ZWaveAPI/Data/0";
HttpResponse httpResponse;
HttpPost httpQuery = new HttpPost(httpsURL);
CustomHttpClient myClient = new CustomHttpClient(myContext);
Log.v("exec", "ready...");
try {
httpResponse = myClient.execute(httpQuery);
if (httpResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
Log.v("exec", "it works ?");
}
Log.v("exec", httpResponse.getStatusLine().getStatusCode()+"");
} catch (Exception ex) {
Log.d("httpError", ex.getMessage());
}
}
}).start();
}
和 CustomHttpClient 类:
public class CustomHttpClient extends DefaultHttpClient {
private static Context appContext = null;
private static Scheme httpsScheme = null;
private static Scheme httpScheme = null;
private static String TAG = "MyHttpClient";
public CustomHttpClient(Context myContext) {
appContext = myContext;
if (httpScheme == null || httpsScheme == null) {
httpScheme = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
httpsScheme = new Scheme("https", mySSLSocketFactory(), 14000);
}
getConnectionManager().getSchemeRegistry().register(httpScheme);
getConnectionManager().getSchemeRegistry().register(httpsScheme);
}
@SuppressWarnings("finally")
private SSLSocketFactory mySSLSocketFactory() {
SSLSocketFactory ret = null;
try {
final KeyStore ks = KeyStore.getInstance("BKS");
final InputStream inputStream = appContext.getResources().openRawResource(R.raw.certs);
ks.load(inputStream, appContext.getString(R.string.store_pass).toCharArray());
inputStream.close();
ret = new SSLSocketFactory(ks);
ret.setHostnameVerifier(myhostnameVerifier);
} catch (UnrecoverableKeyException ex) {
Log.d(TAG, ex.getMessage());
} catch (KeyStoreException ex) {
Log.d(TAG, ex.getMessage());
} catch (KeyManagementException ex) {
Log.d(TAG, ex.getMessage());
} catch (NoSuchAlgorithmException ex) {
Log.d(TAG, ex.getMessage());
} catch (IOException ex) {
Log.d(TAG, ex.getMessage());
} catch (Exception ex) {
Log.d(TAG, ex.getMessage());
} finally {
return ret;
}
}
X509HostnameVerifier myhostnameVerifier = new X509HostnameVerifier() {
@Override
public void verify(String arg0, SSLSocket arg1) throws IOException {
Log.v("X509", "verified "+arg0);
if("z-cloud.z-wave.me" != arg0)
{
//throw new SSLException("Mismatching hostname");
}
}
@Override
public void verify(String arg0, X509Certificate arg1)
throws SSLException {
Log.v("X509", "called 2");
}
@Override
public void verify(String arg0, String[] arg1, String[] arg2)
throws SSLException {
Log.v("X509", "called 3");
}
@Override
public boolean verify(String host, SSLSession session) {
Log.v("X509", "called 4");
return false;
}
};
}
我不知道为什么,但我收到错误 401,但我的登录名和密码很好。我不确定我使用的证书是否正确,但我真的需要它吗?请帮助我,我真的很累尝试发送一个简单的帖子请求......