Android java.net.UnknownHostException: хост не разрешен: адрес_сервера: 443 - PullRequest
0 голосов
/ 01 октября 2010

Я пытаюсь получить XML с сервера через соединение https.Если я делаю это с помощью команды curl

curl -k -A "Mozilla/4.0" https://username:password@server.com/test/infoxml.ashx

соединение успешно, но когда я пробую это в Java на Android, оно не работает.Я использую этот код:

URL url = new URL("https://user:password@server.com");
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic **********************");
conn.setRequestProperty("User-Agent", "Mozilla/4.0");
conn.setRequestProperty("Host", "server.com");
conn.setRequestProperty("Accept", "*/*");

InputStream content = conn.getInputStream();

Как видите, я установил заголовки на основе подробного вывода рабочей команды curl, которая выглядит следующим образом:

* About to connect() to server.com port 443 (#0)
*   Trying (server ip)... connected
* Connected to server.com (server ip) port 443 (#0)
* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS handshake, Server finished (14):
* SSLv3, TLS handshake, Client key exchange (16):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSL connection using AES256-SHA
* Server certificate:
*   subject: C=SI; ST=City; L=City; O=Company d.d; OU=ES; CN=server.com
*   start date: 2010-02-05 00:00:00 GMT
*   expire date: 2011-02-02 23:59:59 GMT
*   common name: server.com (matched)
*   issuer: C=ZA; ST=Western Cape; L=Cape Town; O=Thawte Consulting cc; OU=Certification Services Division; CN=Thawte Premium Server CA; emailAddress=censored
*   SSL certificate verify ok.
* Server auth using Basic with user 'username'
> GET /test/infoxml.ashx HTTP/1.1
> Authorization: Basic ****************************
> User-Agent: Mozilla/4.0
> Host: server.com
> Accept: */*
> 
< HTTP/1.1 200 OK
< Connection: Keep-Alive
< X-Powered-By: ASP.NET
< X-AspNet-Version: 2.0.50727
< Keep-Alive: timeout=5, max=100
< Server: Microsoft-IIS/6.0
< Cache-Control: private
< Set-Cookie: JSESSIONID=abcs8ebwPsf-A-biM7KTs; path=/
< Content-Type: text/xml; charset=utf-8
< Content-Length: 1688
< Date: Thu, 30 Sep 2010 23:16:06 GMT
< 
* Connection #0 to host server.com left intact
* Closing connection #0
* SSLv3, TLS alert, Client hello (1):
<?xml version="1.0"...

I 'Я новичок в этом безопасном соединении, так что будьте спокойны:)

ps извините за мой плохой английский.

1 Ответ

0 голосов
/ 01 октября 2010

Попробуйте что-то вроде следующего.Об обоснованности HttpRequestInterceptor см. в этом блоге "Базовая аутентификация Http с Android" .Я не пробовал код, но это конгломерат рабочего кода, который я использовал вместе с добавленной частью базовой аутентификации.

SchemeRegistry supportedSchemes = new SchemeRegistry();
supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProtocolParams.setUserAgent(params, "Android App");

ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, supportedSchemes);
AbstractHttpClient httpClient = new DefaultHttpClient(connectionManager, params);

HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
    @Override
    public void process(HttpRequest request, HttpContext context)
            throws HttpException, IOException {
        AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
        CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
                ClientContext.CREDS_PROVIDER);
        HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

        if (authState.getAuthScheme() == null) {
            AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
            Credentials creds = credsProvider.getCredentials(authScope);
            if (creds != null) {
                authState.setAuthScheme(new BasicScheme());
                authState.setCredentials(creds);
            }
        }
    }
};

httpClient.addRequestInterceptor(preemptiveAuth, 0);

Credentials creds = new UsernamePasswordCredentials("username", "password");
httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), creds);

HttpHost host = new HttpHost("server.com", 443, "https");
HttpGet httpGet = new HttpGet("https://server.com/test/infoxml.ashx");
HttpResponse httpResponse = httpClient.execute(host, httpGet);

HttpEntity responseEntity = httpResponse.getEntity();
InputStream content = responseEntity.getContent();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...