POST запрос на сервер по https используя SSL

Ответить
skull
Сообщения: 48
Зарегистрирован: 22 апр 2014, 15:49

POST запрос на сервер по https используя SSL

Сообщение skull » 05 фев 2015, 20:07

POST запрос на сервер по https используя установленный сертификат безопасности... Сервер возвращает XML...

GET запрос я смог сделать. Использовал HttpsURLConnection.

Код: Выделить всё

public void authorization(){
        
    
        
        try
        {
    
            
            URL url = new URL("https://myURL.ru/monit/mobile/vehicle/login");
            HttpsURLConnection con;
    
            con= (HttpsURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("accept", "application/xml");
            
            
            
            /////
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] {
              new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) {}
                public void checkServerTrusted(X509Certificate[] chain, String authType) {}
                public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; }
              }
            }, null);
        
            HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
            
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                  public boolean verify(String hostname, SSLSession session) {
                    return true;
                  }
                });
            /////
            
            
                        
            if (isCancelled()) return;
            
            try 
        {
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();
         
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                Log.i("POST-GET", response.toString());
               // ParseV(response.toString());
            }
                catch (IOException e) { e.printStackTrace(); }
        
        }
            
        catch (Exception e) 
            {
                Log.d("Error GetServer", "Message error " + e.toString());  
                Log.i("d", e.toString());
                this.cancel(true);
            }
        
    }
Но вот с POST у меня нечего не выходит :((
Как отправить на сервер POST запрос с параметрами(логин, пароль), используя SSL ? ....

Кто знает не проходите мимо пожалуйста!


Marimarti
Сообщения: 17
Зарегистрирован: 19 дек 2014, 21:29

Re: POST запрос на сервер по https используя SSL

Сообщение Marimarti » 12 фев 2015, 02:19

skull писал(а):Как отправить на сервер POST запрос с параметрами(логин, пароль), используя SSL ?
Пример с рабочего приложения
[syntax=java]private DefaultHttpClient getThreadSafeHttpClient() {
final HttpParams params = new BasicHttpParams();
params.setParameter("http.useragent", "Mozilla/5.0 (Linux; U; Android 1.1; en-us;dream) AppleWebKit/525.10+ (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2");
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
final SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
registry.register(new Scheme("https", sslSocketFactory, 443));
final ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
final DefaultHttpClient httpclient = new DefaultHttpClient(manager, params);
// how to handle retries
final HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
public boolean retryRequest(final IOException exception, final int executionCount, final HttpContext context) {
if (executionCount >= 5) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof NoHttpResponseException) {
// Retry if the server dropped connection on us
return true;
}
if (exception instanceof SSLHandshakeException) {
// Do not retry on SSL handshake exception
return false;
}
final HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
final boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false;
}

};
httpclient.setHttpRequestRetryHandler(myRetryHandler);
return httpclient;
}[/syntax]

[syntax=java]HttpClient httpclient = getThreadSafeHttpClient();
HttpResponse response;
HttpPost httppost = new HttpPost("https://duckduckgo.com/html/");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("q", "duckduckgo" ) );
nameValuePairs.add(new BasicNameValuePair("s", "0" ));
nameValuePairs.add(new BasicNameValuePair("o", "json"));
nameValuePairs.add(new BasicNameValuePair("dc", "-21"));
nameValuePairs.add(new BasicNameValuePair("b", ""));
httppost.addHeader("Host", "duckduckgo.com");
httppost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0");
httppost.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httppost.addHeader("Accept-Encoding", "gzip, deflate");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);

...

[/syntax]

Ответить