powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / peer not authenticated при авторизации вконтакте
4 сообщений из 4, страница 1 из 1
peer not authenticated при авторизации вконтакте
    #38418005
stim644
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Всем привет !
Никак не могу понять, почему у меня возникает ошибка peer not authenticated

Вот код :
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
    	String idapp = "";//id приложения
    String settings = "audio";//запрашиваемые функции
    String redirect_uri = "http://api.vkontakte.ru/blank.html";
    String login = "";//логин
    String pass = "";//пароль
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost post;
    HttpResponse response;
    //составляем url-строку
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("client_id", idapp));
    qparams.add(new BasicNameValuePair("scope", settings));
    qparams.add(new BasicNameValuePair("redirect_uri", redirect_uri));
    qparams.add(new BasicNameValuePair("display", "wap"));
    qparams.add(new BasicNameValuePair("response_type", "token"));
    URI uri = URIUtils.createURI("http", "api.vkontakte.ru", -1, "/oauth/authorize",
    URLEncodedUtils.format(qparams, "UTF-8"), null);
    //запускал в снифере и смотрел редиректы. первый редирект содержит два параметра ip_h и to, которые затем записываются в невидимые поля формы авторизации
    //первый запрос. получаем значения to и ip_h т.д.
    post = new HttpPost(uri);
    response = httpclient.execute(post);
    post.abort();
    String HeaderLocation = response.getFirstHeader("location").getValue();
    URI RedirectUri = new URI(HeaderLocation);
    String ip_h= RedirectUri.getQuery().split("&")[1].split("=")[1];
    String to_h=RedirectUri.getQuery().split("&")[3].split("=")[1];
    //второй запрос. отправляем логин/пароль/to/ip_h
    post = new HttpPost("https://login.vk.com/?act=login&soft=1");
    List <NameValuePair> postform = new ArrayList<NameValuePair>();
    postform.add(new BasicNameValuePair("q", "1"));
    postform.add(new BasicNameValuePair("ip_h", ip_h));
    postform.add(new BasicNameValuePair("from_host", "api.vkontakte.ru"));
    postform.add(new BasicNameValuePair("to", to_h));
    postform.add(new BasicNameValuePair("expire", "0"));	
    postform.add(new BasicNameValuePair("email", login));
    postform.add(new BasicNameValuePair("pass", pass));
    post.setEntity(new UrlEncodedFormEntity(postform, HTTP.UTF_8));
    response = httpclient.execute(post);
    post.abort();
    //Если редирект есть - вход подтвержден. Переход на страницу разрешения доступа к функциям апи
    HeaderLocation = response.getFirstHeader("location").getValue();
    post = new HttpPost(HeaderLocation);
    response = httpclient.execute(post);
    post.abort();
    //подтверждать доступ нужно только при первой авторизации! при все последующий нас автоматически будет перебрасывать на страницу с access_token
    //извлекаем ссылку для подтверждения доступа к функциям..
    String body = EntityUtils.toString(response.getEntity());
    String form_action= "<form method=\"POST\" action=\"";
    int uri_start_index=body.indexOf(form_action)+form_action.length();
    int uri_end_index=uri_start_index+body.substring(uri_start_index).indexOf('>')-1;
    String grant_access_uri="http://api.vkontakte.ru"+body.substring(uri_start_index,uri_end_index);
    //отправляем ссылку(для первой авторизации) или переходим по редиректу(если приложению уже был разрешен доступ)
    post = new HttpPost(grant_access_uri);
    response = httpclient.execute(post);
    post.abort();
    //в последнем редиректер содержится необходимый нам access_token
    String access_token = response.getFirstHeader("location").getValue().split("#")[1].split("&")[0].split("=")[1];
    System.out.println(access_token);
    response = httpclient.execute(post);



Полный стэк трейс :

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
    Exception in thread "main" javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
    at com.sun.net.ssl.internal.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:352)
    at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:131)
    at org.apache.http.conn.ssl.SSLSocketFactory.verifyHostname(SSLSocketFactory.java:648)
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:623)
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:469)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:179)
    at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:304)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:610)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:444)
    at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:864)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:58)
    at test.VK.login(VK.java:103)
    at test.VK.test(VK.java:135)
    at test.VK.main(VK.java:145)



Подскажите пожалуйста.
...
Рейтинг: 0 / 0
peer not authenticated при авторизации вконтакте
    #38418087
забыл ник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
надо импортировать сертификат, по стектрейсу же можно догадаться
...
Рейтинг: 0 / 0
peer not authenticated при авторизации вконтакте
    #38418529
stim644
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
забыл ник,

Сертификат вконтакте ?
...
Рейтинг: 0 / 0
peer not authenticated при авторизации вконтакте
    #38422198
stim644
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Решил, добавив класс
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
public class InsecureHttpClientFactory {
    
    DefaultHttpClient hc;
        
    public DefaultHttpClient buildHttpClient() throws NoSuchAlgorithmException,
                                                      KeyManagementException,
                                                      KeyStoreException,
                                                      UnrecoverableKeyException {
        hc = new DefaultHttpClient();
        //configureProxy();
        configureCookieStore();
        configureSSLHandling();
        return hc;
    }

    private void configureProxy() {
        HttpHost proxy = new HttpHost("proxy.example.org", 3182);
        hc.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    private void configureCookieStore() {
        CookieStore cStore = new BasicCookieStore();
        hc.setCookieStore(cStore);
    }

    private void configureSSLHandling() throws NoSuchAlgorithmException,
                                               KeyManagementException,
                                               KeyStoreException,
                                               UnrecoverableKeyException {
        Scheme http =
            new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
        SSLSocketFactory sf = buildSSLSocketFactory();
        Scheme https = new Scheme("https", 443, sf);
        SchemeRegistry sr = hc.getConnectionManager().getSchemeRegistry();
        sr.register(http);
        sr.register(https);
    }

    private SSLSocketFactory buildSSLSocketFactory() throws NoSuchAlgorithmException,
                                                            KeyManagementException,
                                                            KeyStoreException,
                                                            UnrecoverableKeyException {
        TrustStrategy ts = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates,
                                     String s) throws CertificateException {
                return true; // heck yea!
            }
        };

        SSLSocketFactory sf = null;

        try {
            /* build socket factory with hostname verification turned off. */
            sf =
 new SSLSocketFactory(ts, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return sf;
    }

}
...
Рейтинг: 0 / 0
4 сообщений из 4, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / peer not authenticated при авторизации вконтакте
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]