package com.example.httppostexample;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;


public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Information().execute();

}


public class Information extends AsyncTask<String, String, String> {

@Override
protected String doInBackground(String... params) {

try{

// Load CAs from an InputStream // (could be from a resource or ByteArrayInputStream or ...)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.lesstif_rootca); // InputStream input = openRawResource(R.raw.lesstif_rootca)) //FileInputStream caInput = (FileInputStream) getResources().openRawResource( R.raw.lesstif_rootca);
// InputStream caInput = new BufferedInputStream(new FileInputStream(file)); // caInput = openFileInput("lesstif_rootca.crt");
/* ByteArrayInputStream derInputStream = new ByteArrayInputStream(aaa.getBytes()); X509Certificate ca = (X509Certificate) cf.generateCertificate(derInputStream); derInputStream.close(); */

InputStream assetFileDescriptor = getAssets().open("aaaa.cer");
InputStream caInput = new BufferedInputStream(assetFileDescriptor);
Certificate ca ;
//X509Certificate ca;

try {
ca = cf.generateCertificate(caInput);
//ca = (X509Certificate) cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());

} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null); //String pass = "xxxxx";//"";// keyStore.load(null, pass.toCharArray());
keyStore.setCertificateEntry("ca", ca); // System.out.println(ca);

// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);

// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null); //context.init(null, trustAllCerts, new java.security.SecureRandom()); context.init(null, trustAllCerts1, new java.security.SecureRandom());

// Tell the URLConnection to use a SocketFactory from our SSLContext
//URL url = new URL("https://x.x.x.x/Ousers");
URL url = new URL("https://www.kt.com/");
HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();

urlConnection.setSSLSocketFactory(context.getSocketFactory()); //urlConnection.setDefaultSSLSocketFactory(context.getSocketFactory());

/* urlConnection.setHostnameVerifier(new HostnameVerifier() {
/* @Override
public boolean verify(String hostname, SSLSession session) {
return true;
}*/
/* @Override
public boolean verify(String hostname, SSLSession session) {
HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
return hv.verify("www.kt.com", session);
}*/
//}); */

JSONObject jobj=new JSONObject();

jobj.put("username","11112");
jobj.put("password","11112");
jobj.put("email","jssolution_onn");
jobj.put("info","jssolution_sun");

Log.e("json string :",jobj.toString());

byte[] postData = jobj.toString().getBytes();

urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);

urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");

OutputStream out = urlConnection.getOutputStream();

out.write(postData);
out.close();

InputStream in = urlConnection.getInputStream(); //copyInputStreamToOutputStream(in, System.out);
Log.e("response_u :",in.toString());

String temp = ((HttpsURLConnection)urlConnection).getResponseMessage();
Log.e("response :",temp);

} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}

// ------------------------------아래는 참고만-----------------------------------------------

public class SSLContextManager
{
public SSLContext getSSLContext(Context context) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, KeyManagementException, NoSuchProviderException
{
// Load CAs from an InputStream
CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
InputStream cert = context.getResources().openRawResource(R.raw.lesstif_rootca); // Place your 'my_cert.crt' file in `res/raw`
Certificate ca;
try
{
ca = cf.generateCertificate(cert);
}
finally
{
cert.close();
}

// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);

// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);

// Create an SSLContext that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);

return sslContext;
}

public SSLContext getTrustAllSSLContext() throws NoSuchAlgorithmException, KeyManagementException
{
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}

@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType){
}

@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};

// Install the all-trusting trust manager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

return sslContext;
}
}

private TrustManager[] getWrappedTrustManagers(TrustManager[] trustManagers) {
final X509TrustManager originalTrustManager = (X509TrustManager) trustManagers[0];
return new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return originalTrustManager.getAcceptedIssuers();
}

public void checkClientTrusted(X509Certificate[] certs, String authType) {
try {
if (certs != null && certs.length > 0){
certs[0].checkValidity();
} else {
originalTrustManager.checkClientTrusted(certs, authType);
}
} catch (CertificateException e) {
Log.w("checkClientTrusted", e.toString());
}
}

public void checkServerTrusted(X509Certificate[] certs, String authType) {
try {
if (certs != null && certs.length > 0){
certs[0].checkValidity();
} else {
originalTrustManager.checkServerTrusted(certs, authType);
}
} catch (CertificateException e) {
Log.w("checkServerTrusted", e.toString());
}
}
}
};
}


TrustManager[] trustAllCerts1 = new TrustManager[] {
new X509TrustManager() {

@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}

}
};

TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}

@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType){
}

@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};

}










}