ȸ¿ø°¡ÀԡžÆÀ̵ð/ºñ¹øã±â
ȨÀ¸·Î

http ¿äû [Android]
7³â Àü
¼­·Ð
ÇöÀç ½ÃÁß¿¡ ³ª¿Í ÀÖ´Â ¾Èµå·ÎÀ̵å Ã¥Àº ¸ðµÎ Http·Î µ¥ÀÌÅ͸¦ ¿äûÇÏ´Â ¿¹Á¦¸¸ ¼ö·ÏÇÏ°í ÀÖ´Ù. ÇÏÁö¸¸ ¾Èµå·ÎÀÌµå ¾ÛÀ» °³¹ßÇÒ ¶§ http ¿äû¸¸ ó¸®ÇÏ´Â °ÍÀÌ ¾Æ´Ï´Ù. https ¿äûÀ» http¿Í µ¿ÀÏÇÏ°Ô »ç¿ëÇÒ¼ö´Â ¾ø´Ù. À̹ø ÇÁ·ÎÁ§Æ®¿¡¼­ https·Î ·Î±×ÀÎ °ü·Ã ÀÛ¾÷À» Çϸ鼭 ¿ì¸®°¡ ¾Èµå·ÎÀ̵带 °³¹ßÇÒ ¶§ ÈçÈ÷ »ç¿ëÇÏ´ÂHttpClient·Î https¸¦ ¿äûÇÒ ¼ö ¾ø´Ù´Â °ÍÀ» È®ÀÎÇÏ°í ¹æ¹ýÀ» ã¾Æ¼­ ÇØ°áÇߴµ¥ ±× ¹æ¹ý¿¡ ´ëÇؼ­ Æ÷½ºÆÃÇÏ°íÀÚ ÇÑ´Ù.

Https ¼­¹ö±¸Ãà

ù¹ø°·Î ¿ì¸®°¡ ÇؾßÇÒ ÀÏÀº Https ¼­¹ö¸¦ ±¸ÃàÇؾßÇÑ´Ù. ÇÏÁö¸¸ °³ÀÎ ¾Û °³¹ßÀÚ´Â ´ëºÎºÐ ¼­¹ö¸¦ °¡Áö°í ÀÖÁö ¾Ê°Å³ª, ¼­¹ö ÀÛ¾÷À» Çϱâ Èûµç »óȲÀÌ´Ù. ±×·¡¼­ ÀÌÀü Æ÷½ºÆÿ¡ OpenSSL°ú Node.js¸¦ »ç¿ëÇؼ­ Https ¼­¹ö¸¦ ±¸ÃàÇÒ ¼ö ÀÖ´Â ¹æ¹ýÀ» ¼Ò°³Çß´Ù. http://blog.saltfactory.net/221 ±ÛÀ» ÂüÁ¶Çؼ­ Https ¼­¹ö¸¦ ¸¸µé¾îº¸ÀÚ. https·Î ·Î±×ÀÎÇÏ´Â ¿¹Á¦¸¦ ¸¸µé°ÍÀ̱⠶§¹®¿¡ ´ÙÀ½°ú °°ÀÌ POST·Î /login ¿äûÀÌ µé¾î¿À´Â ºÎºÐÀ» ¼öÁ¤ÇÑ´Ù.

var http=require('http'),
    https = require('https'),
    express = require('express'),
    fs = require('fs');

var options = {
    key: fs.readFileSync('key.pem'),
    cert: fs.readFileSync('cert.pem')
};


var port1 = 80;
var port2 = 443;

var app = express();
app.use(express.urlencoded());
app.use(express.logger());

http.createServer(app).listen(port1, function(){
  console.log("Express server listening on port " + port1);
});


https.createServer(options, app).listen(port2, function(){
  console.log("Express server listening on port " + port2);
});


app.get('/', function (req, res) {
    res.writeHead(200, {'Content-Type' : 'text/html'});
    res.write('<h3>Welcome</h3>');
    res.write('<a href="/login">Please login</a>');
    res.end();
});

app.get('/login', function (req, res){
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<h3>Login</h3>');
    res.write('<form method="POST" action="/login">');
    res.write('<label name="userId">UserId : </label>')
    res.write('<input type="text" name="userId"><br/>');
    res.write('<label name="password">Password : </label>')
    res.write('<input type="password" name="password"><br/>');
    res.write('<input type="submit" name="login" value="Login">');
    res.write('</form>');
    res.end();
})

// app.post('/login', function (req, res){
//  var userId = req.param("userId");
//  var password = req.param("password")
//
//  res.writeHead(200, {'Content-Type': 'text/html'});
//  res.write('Thank you, '+userId+', you are now logged in.');
//  res.write('<p><a href="/"> back home</a>');
//  res.end();
// });

app.post('/login', function (req, res){
        var userId = req.param("userId");
        var password = req.param("password")

    res.json({userId:userId, password:password});
});
Å×½ºÆ® ÇÁ·ÎÁ§Æ® »ý¼º ¹× HttpClient ¿äû

Https ¿äûÀ» Å×½ºÆ®Çϱâ À§Çؼ­ °£´ÜÇÑ ¾Èµå·ÎÀ̵å ÇÁ·ÎÁ§Æ®¸¦ »ý¼ºÇÑ´Ù. ¹öÆ°À» °¡Áö°í ÀÖ°í ¹öÆ°À» ´©¸£¸é https¸¦ ¿äûÇÏ´Â °£´ÜÇÑ ¿¹Á¦ÀÌ´Ù. ÃÖÁ¾ ¼Ò½ºÄÚµå´Â github¿¡ °ø°³ÇÒ ¿¹Á¤ÀÌ´Ù. ¿ì¼± °£´ÜÈ÷ ¾Èµå·ÎÀ̵å ÇÁ·ÎÁ§Æ®¸¦ »ý¼ºÇؼ­ onCreate ¸Þ¼Òµå ¾È¿¡ ´ÙÀ½°ú °°ÀÌ ¹öÆ°À» Ŭ¸¯ÇÒ¶§ ¿ÂŬ¸¯ ¸®½º³Ê¸¦ µî·ÏÇÑ´Ù. ¼­¹ö·Î ³Ñ±â´Â µ¥ÀÌÅÍ´Â userId¿Í password ÀÌ´Ù. ¼­¹ö·Î µ¥ÀÌÅ͸¦ ³Ñ±â¸é json µ¥ÀÌÅ͸¦ ¹Þ¾Æ¿Í¼­ console¿¡ Ãâ·ÂÇÏ´Â °£´ÜÇÑ ÄÚµåÀÌ´Ù.

HttpClient¸¦ DefaultHttpClient·Î ¿äû

ÈçÈ÷ ¿ì¸®°¡ http ¿äûÀ» ó¸®ÇÒ ¶§ DefaultHttpClient¸¦ »ç¿ëÇÑ´Ù. ´ÙÀ½ ÄÚµå´Â HttpClient¸¦ DefaultHttpClient·Î »ç¿ëÇÏ´Â ¿¹Á¦ÀÌ´Ù. ¿©±â¼­ urlStringÀº ¿©·¯ºÐµéÀÌ Å×½ºÆ®ÇÏ´Â ip¸¦ ÀÔ·ÂÇÏ¸é µÈ´Ù. °øÀ¯±â·Î »ç¼³³×Æ®¿öÅ©¿¡¼­ Å×½ºÆ®¸¦ ÁøÇàÇ߱⠶§¹®¿¡ ÇöÀç ¸ÆºÏÇÁ·ÎÀÇ http ¼­¹ö ip´Â 192.168.1.101 ÀÌ´Ù.

public class MyActivity extends Activity {
    final String TAG = "saltfactory.net";

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button buttonGet = (Button) findViewById(R.id.sf_button_post);
        buttonGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        HttpClient httpClient = new DefaultHttpClient();


                        String urlString = "http://192.168.1.101/login";
                        try {
                            URI url = new URI(urlString);

                            HttpPost httpPost = new HttpPost();
                            httpPost.setURI(url);

                            List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(2);
                            nameValuePairs.add(new BasicNameValuePair("userId", "saltfactory"));
                            nameValuePairs.add(new BasicNameValuePair("password", "password"));

                            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


                            HttpResponse response = httpClient.execute(httpPost);
                            String responseString = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);

                            Log.d(TAG, responseString);

                        } catch (URISyntaxException e) {
                            Log.e(TAG, e.getLocalizedMessage());
                            e.printStackTrace();
                        } catch (ClientProtocolException e) {
                            Log.e(TAG, e.getLocalizedMessage());
                            e.printStackTrace();
                        } catch (IOException e) {
                            Log.e(TAG, e.getLocalizedMessage());
                            e.printStackTrace();
                        }

                    }
                };


                thread.start();
            }
        });

    }

}
°á°ú´Â ´ÙÀ½°ú °°´Ù. ´Ü¼øÇÏ°Ô http¿äûÀ» DefaultHttpClient·Î ¿äûÇÑ µ¥ÀÌÅÍ´Â POST¸¦ Á¤»óÀûÀ¸·Î ó¸®ÇÏ°í ÀÀ´äÀ» jsonÀ¸·Î ¹Þ¾Æ ¿Ô´Ù.



±×·¯¸é http ¿äûÀÌ ¾Æ´Ñ https¸¦ DefaultHttpClient·Î ¿äûÇÏ¸é ¾î¶² °á°ú°¡ ³ªÅ¸³ª´ÂÁö »ìÆ캸ÀÚ. urlStringÀ» http://¿¡¼­ https://·Î º¯°æÇÏ°í ½ÇÇàÇÑ´Ù.



°á°ú´Â No Peer Certificate¶ó´Â ¿¡·¯¸¦ ¹ß»ý½ÃÅ°¸é¼­ ¿äûÀ» Á¦´ë·Î ¿Ï·áÇÏÁö ¸øÇÑ´Ù´Â °ÍÀ» È®ÀÎÇÒ ¼ö ÀÖ´Ù. ¿Ö³Ä¸é https´Â ÀÎÁõ¼­¸¦ ÀÎÁõÇÏ´Â °úÁ¤ÀÌ ÀÖ¾î¾ßÇϴµ¥ http´Â ´Ü¼ø http ¿äû¸¸ ó¸®Çϱ⠶§¹®ÀÌ´Ù.

HttpClient¿¡ SSLSocketFactory ¼Ó¼º Ãß°¡

ÈçÈ÷ ¿ì¸®°¡ Http ¿äûÀ» ÇÒ ¶§ »ç¿ëÇÏ´Â HttpClient´Â DefaultHttpClient ÀÌ´Ù. ÇÏÁö¸¸ ÀÌ·¸°Ô ±¸ÇöÇϸé Https ¿äûÀ» ÇÒ ¼ö ¾ø´Ù. ±×·¡¼­ HttpClient¿¡ SSLSocketFactory¸¦ »ç¿ëÇؼ­ SSL ÀÎÁõÀ» ÇÒ ¼ö ÀÖµµ·Ï ¼Ó¼ºÀ» Ãß°¡ÇÑ´Ù. ¸ÕÀú SSLSocketFactory¸¦ »ó¼Ó¹Þ¾Æ ´ÙÀ½°ú °°ÀÌ SSLSocketFactory¸¦ ¸¸µç´Ù.

package net.saltfactory.tutorial.httpsdemo;

import org.apache.http.conn.ssl.SSLSocketFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
* Created by saltfactory on 1/27/14.
*/
public class SFSSLSocketFactory extends SSLSocketFactory {
    SSLContext sslContext = SSLContext.getInstance("TLS");

    public SFSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(truststore);

        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }


        };

        sslContext.init(null, new TrustManager[]{tm}, null);
//        sslContext.init(null, new TrustManager[] { tm }, new SecureRandom());
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }
}
´ÙÀ½Àº https¸¦ ¿äûÇϱâ À§Çؼ­ DefaultHttpClient¸¦ »ý¼ºÇÑ °÷¿¡ ´ÙÀ½°ú °°ÀÌ ¼öÁ¤ÇÑ´Ù.

package net.saltfactory.tutorial.httpsdemo;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;

public class MyActivity extends Activity {
    final String TAG = "saltfactory.net";

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button buttonGet = (Button) findViewById(R.id.sf_button_post);
        buttonGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        //HttpClient HttpClient = new DefaultHttpClient();
                        HttpClient httpClient = getHttpClient();


                        String urlString = "https://192.168.1.101/login";
                        try {
                            URI url = new URI(urlString);

                            HttpPost httpPost = new HttpPost();
                            httpPost.setURI(url);

                            List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(2);
                            nameValuePairs.add(new BasicNameValuePair("userId", "saltfactory"));
                            nameValuePairs.add(new BasicNameValuePair("password", "password"));

                            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


                            HttpResponse response = httpClient.execute(httpPost);
                            String responseString = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);

                            Log.d(TAG, responseString);

                        } catch (URISyntaxException e) {
                            Log.e(TAG, e.getLocalizedMessage());
                            e.printStackTrace();
                        } catch (ClientProtocolException e) {
                            Log.e(TAG, e.getLocalizedMessage());
                            e.printStackTrace();
                        } catch (IOException e) {
                            Log.e(TAG, e.getLocalizedMessage());
                            e.printStackTrace();
                        }

                    }
                };

                thread.start();
            }
        });


    }

    private HttpClient getHttpClient() {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            SSLSocketFactory sf = new SFSSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

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

            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

            return new DefaultHttpClient(ccm, params);
        } catch (Exception e) {
            return new DefaultHttpClient();
        }
    }
}
ÀÌ·¸°Ô Äڵ带 SFSSLFactory¸¦ Ãß°¡Çؼ­ HttpClient¿¡ SchemeÀ» µÎ°¡Áö·Î Ãß°¡Çß´Ù. http¿Í https¸¦ ó¸®ÇÒ ¼ö ÀÖ´Â SchemeÀ» °¡Áö°Ô ÇÏ¿´°í SSL ÀÎÁõÀ» TLS·Î HostNameVerifier¸¦ ó¸®ÇÏ°Ô Çß´Ù. ÀÌÁ¦ ´Ù½Ã ½ÇÇàÀ» Çغ¸ÀÚ.



Á¤»óÀûÀ¸·Î https·Î µ¥ÀÌÅ͸¦ ¿äûÇؼ­ ÀÀ´äÀ» ¹Þ¾Æ ¿Â °ÍÀ» È®ÀÎÇÒ ¼ö ÀÖ´Ù. WireShark·Î ÆÐŶÀ» ĸÃÄÇغ¸¸é Å×½ºÆ®¸¦ ÁøÇàÇÑ ¾Èµå·ÎÀÌµå µð¹ÙÀ̽º¿¡¼­ https·Î ¿äûÇß°í TLS·Î º¸¾È ¿äûÀ» ó¸®ÇÑ °ÍÀ» È®ÀÎÇÒ ¼ö ÀÖ´Ù.



HttpURLConnection »ç¿ë

¾Èµå·ÎÀ̵忡¼­ Http ¿äûÀ» ó¸®Çϴµ¥ HttpClient¸¦ »ç¿ëÇÏ´Â ¹æ¹ý ¸»°í ¶Ç´Ù¸¥ ¹æ¹ýÀÌ Àִµ¥ ¹Ù·Î HttpURLConnectionÀ» »ç¿ëÇÏ´Â ¹æ¹ýÀÌ´Ù. À§¿¡¼­ DefaultHttpClient¸¦ »ç¿ëÇÑ Äڵ带 ´ÙÀ½°ú °°ÀÌ HttpURLConnectionÀ¸·Î º¯°æÇÑ´Ù.

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button buttonGet = (Button) findViewById(R.id.sf_button_post);
        buttonGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                Thread thread = new Thread() {
                    @Override
                    public void run() {
//                      HttpClient HttpClient = new DefaultHttpClient();


                        String urlString = "http://192.168.1.101/login";
//                        try {
//                            URI url = new URI(urlString);
//
//                            HttpPost httpPost = new HttpPost();
//                            httpPost.setURI(url);
//
//                            List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(2);
//                            nameValuePairs.add(new BasicNameValuePair("userId", "saltfactory"));
//                            nameValuePairs.add(new BasicNameValuePair("password", "password"));
//
//                            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//
//
//                            HttpResponse response = httpClient.execute(httpPost);
//                            String responseString = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
//
//                            Log.d(TAG, responseString);
//
//                        } catch (URISyntaxException e) {
//                            Log.e(TAG, e.getLocalizedMessage());
//                            e.printStackTrace();
//                        } catch (ClientProtocolException e) {
//                            Log.e(TAG, e.getLocalizedMessage());
//                            e.printStackTrace();
//                        } catch (IOException e) {
//                            Log.e(TAG, e.getLocalizedMessage());
//                            e.printStackTrace();
//                        }
//
                        try {
                            URL url = new URL(urlString);

                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                            connection.setRequestMethod("POST");
                            connection.setDoInput(true);
                            connection.setDoOutput(true);

                            List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(2);
                            nameValuePairs.add(new BasicNameValuePair("userId", "saltfactory"));
                            nameValuePairs.add(new BasicNameValuePair("password", "password"));

                            OutputStream outputStream = connection.getOutputStream();
                            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                            bufferedWriter.write(getURLQuery(nameValuePairs));
                            bufferedWriter.flush();
                            bufferedWriter.close();
                            outputStream.close();

                            connection.connect();


                            StringBuilder responseStringBuilder = new StringBuilder();
                            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
                                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                                for (;;){
                                    String stringLine = bufferedReader.readLine();
                                    if (stringLine == null ) break;
                                    responseStringBuilder.append(stringLine + '\n');
                                }
                                bufferedReader.close();
                            }

                            connection.disconnect();

                            Log.d(TAG, responseStringBuilder.toString());



                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }


                    }
                };

                thread.start();
            }
        });
    }

    private String getURLQuery(List<BasicNameValuePair> params){
        StringBuilder stringBuilder = new StringBuilder();
        boolean first = true;

        for (BasicNameValuePair pair : params)
        {
            if (first)
                first = false;
            else
                stringBuilder.append("&");

            try {
                stringBuilder.append(URLEncoder.encode(pair.getName(), "UTF-8"));
                stringBuilder.append("=");
                stringBuilder.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        return stringBuilder.toString();
    }
µð¹ÙÀ̽º¿¡¼­ ½ÇÇàÀ» Çغ¸ÀÚ. ¾Õ¿¡¼­ HttpClient¿¡ DefaultHttpClient·Î ¿äûÇÑ °á°ú¸¦ HttpURLConnectionÀ¸·Î µ¿ÀÏÇÏ°Ô ¹ÞÀ» ¼ö ÀÖ´Â °ÍÀ» È®ÀÎÇÒ ¼ö ÀÖ´Ù.



HttpsURLConnectionÀ» »ç¿ëÇϱâ

¾Õ¿¡¼­ »ìÆìºÃµí ¾Èµå·ÎÀ̵忡¼­ http¿äûÀ» HttpClient¸¦ »ç¿ëÇÏ´Â ´ë½Å¿¡ HttpURLConnectionÀ» »ç¿ëÇϵí, Https¸¦ ¿äûÇÏ´Â ¹æ¹ýÀº HttpClient¸¦ SSLSocketFactory¸¦ »ç¿ëÇÏ´Â ¹æ¹ý ¸»°íµµ HttpsURLConnectionÀ» ÀÌ¿ëÇÏ´Â ¹æ¹ýÀÌ ÀÖ´Ù. À§ÀÇ HttpURLConnectionÀ» »ç¿ëÇÑ Äڵ带 ´ÙÀ½°ú °°ÀÌ ¼öÁ¤ÇÑ´Ù.

package net.saltfactory.tutorial.httpsdemo;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;

public class MyActivity extends Activity {
    final String TAG = "saltfactory.net";

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button buttonGet = (Button) findViewById(R.id.sf_button_post);
        buttonGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        //HttpClient HttpClient = new DefaultHttpClient();
//                        HttpClient httpClient = getHttpClient();

                        String urlString = "https://192.168.1.101/login";

                        try {
                            URL url = new URL(urlString);

//                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                            trustAllHosts();

                            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
                            httpsURLConnection.setHostnameVerifier(new HostnameVerifier() {
                                @Override
                                public boolean verify(String s, SSLSession sslSession) {
                                    return true;
                                }
                            });

                            HttpURLConnection connection = httpsURLConnection;

                            connection.setRequestMethod("POST");
                            connection.setDoInput(true);
                            connection.setDoOutput(true);

                            List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(2);
                            nameValuePairs.add(new BasicNameValuePair("userId", "saltfactory"));
                            nameValuePairs.add(new BasicNameValuePair("password", "password"));

                            OutputStream outputStream = connection.getOutputStream();
                            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                            bufferedWriter.write(getURLQuery(nameValuePairs));
                            bufferedWriter.flush();
                            bufferedWriter.close();
                            outputStream.close();

                            connection.connect();


                            StringBuilder responseStringBuilder = new StringBuilder();
                            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
                                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                                for (;;){
                                    String stringLine = bufferedReader.readLine();
                                    if (stringLine == null ) break;
                                    responseStringBuilder.append(stringLine + '\n');
                                }
                                bufferedReader.close();
                            }

                            connection.disconnect();

                            Log.d(TAG, responseStringBuilder.toString());



                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }


                    }
                };

                thread.start();
            }
        });

    }

    private static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] chain,
                    String authType)
                    throws java.security.cert.CertificateException {
                // TODO Auto-generated method stub

            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] chain,
                    String authType)
                    throws java.security.cert.CertificateException {
                // TODO Auto-generated method stub

            }
        }};

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getURLQuery(List<BasicNameValuePair> params){
        StringBuilder stringBuilder = new StringBuilder();
        boolean first = true;

        for (BasicNameValuePair pair : params)
        {
            if (first)
                first = false;
            else
                stringBuilder.append("&");

            try {
                stringBuilder.append(URLEncoder.encode(pair.getName(), "UTF-8"));
                stringBuilder.append("=");
                stringBuilder.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        return stringBuilder.toString();
    }


}
ÀÌÁ¦ µð¹ÙÀ̽º¿¡¼­ ½ÇÇàÀ» Çغ¸ÀÚ. ´ÙÀ½°ú °°ÀÌ HttpURLConnectionÀ» ½ÇÇàÇÑ °á°ú¿Í µ¿ÀÏÇÏ°Ô µ¿ÀÛÇÏ´Â °ÍÀ» È®ÀÎ ÇÒ ¼ö ÀÖ´Ù.



°á·Ð
¿ì¸®´Â ¾Èµå·ÎÀÌµå ¾ÛÀ» °³¹ßÇÒ ¶§ Http ¿äûÀ» HttpClient¸¦ »ç¿ëÇß´Ù. ±×¸®°í DefaultHttpClient¸¦ »ç¿ëÇؼ­ POST³ª GET ¿äûÀ» Çߴµ¥ Http ¿äûÀº HttpURLConnectionÀ¸·Îµµ ÇÒ ¼ö ÀÖ´Ù´Â °ÍÀ» È®ÀÎ Çß´Ù. ÇÏÁö¸¸ Https´Â DefaultHttpClient¿Í HttpURLConnectionÀ» »ç¿ëÇÒ ¼ö ¾ø´Ù. ÀÌÀ¯´Â ÀÎÁõó¸®ÇÏ´Â ¼Ó¼ºÀÌ ÀÖ¾î¾ßÇϴµ¥ DefaultHttpClient¿Í HttpURLConnectionÀº SSL ÀÎÁõ 󸮰¡ ¾ø±â ¶§¹®ÀÌ´Ù. ±×·¡¼­ HttpClient¿¡ SSLSocketFactory¸¦ »ç¿ëÇß°í HttpURLConnectionÀ» HttpsURLConnectionÀ¸·Î »ç¿ëÇؼ­ ÀÎÁõó¸® ¼Ó¼ºÀ» °¡Áö°Ô ÇÒ ¼ö ÀÖ´Ù´Â °ÍÀ» È®ÀÎÇß´Ù.

¼Ò½ºÄÚµå
https://github.com/saltfactory/saltfactory-android-tutorial/tree/sf-https-demo
Âü°í
http://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post
http://cafe.naver.com/jzsdn/21091
http://stackoverflow.com/questions/2642777/trusting-all-certificates-using-httpclient-over-https
ÃßõÃßõ : 281 Ãßõ ¸ñ·Ï
¹øÈ£ Á¦¸ñ
1,226
android | ²¨Áø È­¸é¿¡¼­ ¾Û ½ÇÇàÇϱâ / Àáµç È­¸é ±ú¿ì±â / Àá±Ý È­¸é À§·Î ½ÇÇà/
1,225
android ÇöÀç WebView¿¡¼­ ¿ÜºÎ ÆäÀÌÁö ºÒ·¯¿À±â / WebView »õâ ¶ç¿ìÁö ¾Ê±â / WebViewClient
1,224
Activity ¸¦ dialog style·Î ¸¸µé±â
1,223
webview ¾Æ·¡ button ³Ö±â
1,222
webview scroll ±â´É ¸·±â(touch´Â µÊ)
1,221
Service µî·ÏÇϱâ
1,220
booting ÈÄ¿¡ ÀÚµ¿À¸·Î ½ÇÇà µÇ´Â app ¸¸µé±â
1,219
[Android] Intent È°¿ë ¿¹½Ã
1,218
Android ¼³Ä¡µÈ ¾îÇà ¸ñ·Ï PackageInfo¸¦ ÅëÇØ °¡Á®¿À±â ¹× ´Ù¸¥ ¾îÇà ½ÇÇà
1,217
[ANDROID(¾Èµå·ÎÀ̵å) ¾Û °³¹ß ±âÃÊ] MEDIAPLAYER À½¾Ç Àç»ýÇϱâ
1,216
[¾Èµå·ÎÀ̵å] ¿ÜºÎ ¾Û ½ÇÇà
1,215
¾Èµå·ÎÀÌµå ¼º´ÉÀ» À§ÇÑ ¼³°è
1,214
ÆÄÀÏ ¾÷·Îµå ¹× ÆĶó¸ÞÅÍ Àü¼Û (sending file & parameters by MultipartEntity / post)
1,213
MediaPlayer °¡·ÎÀÏ ¶§ UI ¼û±â°í Ç®½ºÅ©¸° ¸¸µé±â
1,212
À¥ºä¿¡¼­ html ÅÂ±× ¾ø¾Ö´Â ¹ý(Remove the html tag on loading web page in WebView)
1,211
´Ù¸¥ ¾Û ½ÇÇàÇϰųª Ç÷¹ÀÌ ½ºÅä¾î·Î À̵¿(Launch another app by code)
1,210
À¥ ºä¿¡¼­ ÅÂ±× Á¤º¸ ÃàÃâÇϱâ(Get the information of html tag in WebView of android)
1,209
ÀÚµ¿À¸·Î ¿¡µðÆ®ºä¿¡ Æ÷Ä¿½º µÇ´Â °Í ¸·±â
1,208
addJavascriptInterface ¿À·ù(Android WebView.addJavascriptInterface not Working)
1,207
Ä¿½ºÅÒ Å佺Ʈ ¶ç¿ì±â(To show Custom Toast)
1,206
À¥¿¡¼­ ÆÄÀÏ »çÀÌÁî¿Í ÄÜÅÙÆ®(ÄÁÅÙÃ÷) ŸÀÔ ¾Ë¾Æº¸´Â »ùÇÃÄÚµå
1,205
¾Èµå·ÎÀ̵å ÅؽºÆ® ºä¿¡¼­ Áö¿øÇÏ´Â HTML ű׵é
1,204
ÀÎÅÍ³Ý ÁÖ¼Ò À¯È¿¼º °Ë»ç (regular expression for url)
1,203
SpannableStringÀ¸·Î ÅؽºÆ® ºä¿¡ ¾ÆÀÌÄÜ ³Ö´Â ¹ý
1,202
½ÇÇà°¡´ÉÇÑ ¾Û ¸ñ·Ï (Get launchable apps in android)
1,201
HTMLÀ» ¾Èµå·ÎÀ̵å À¥ºä¿¡ ¸ðµÎ º¸ÀÌ°Ô Çϱâ Using WebView ViewPort in android
1,200
so ÆÄÀÏ ¾Èµå·ÎÀÌµå ½ºÆ©µð¿À¿¡¼­ »ç¿ëÇÏ´Â ¹ý
1,199
[¾Èµå·ÎÀ̵å] È­¸é »çÀÌÁî ±¸Çϱâ
1,198
[¾Èµå·ÎÀ̵å] ¾Èµå·ÎÀÌµå ½ºÆ©µð¿À¿¡¼­ ºôµå ÆÄÀÏ À̸§ ¼öÁ¤Çϱâ.
1,197
¿ÜºÎ ¾Û ½ÇÇà½ÃÅ°±â (launch external app in android)
¸ñ·Ï
¹ÂÁ÷Æ®·ÎÆ® ºÎ»ê±¤¿ª½Ã ºÎ»êÁø±¸ °¡¾ßµ¿ ¤Ó °³ÀÎÁ¤º¸Ãë±Þ¹æħ
Copyright ¨Ï musictrot All rights reserved.