Skip to main content

Java Code Examples for javax.net.ssl.HttpsURLConnection

The following code examples are extracted from open source projects. You can click to vote up the examples you like. Your votes will be used in an intelligent system to get more and better code examples. Thanks for your votes!
Code Example 1:
  9 
vote
From project ADFS, under directory /adfs-hdfs-project/adfs-hdfs/src/main/java/org/apache/hadoop/hdfs/.
Source HsftpFileSystem.java
@Override protected HttpURLConnection openConnection(String path,String query) throws IOException {
  query=addDelegationTokenParam(query);
  final URL url=new URL("https",nnAddr.getHostName(),nnAddr.getPort(),path + '?' + query);
  HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();
  conn.setHostnameVerifier(new DummyHostnameVerifier());
  return (HttpURLConnection)conn;
}
 

Code Example 2:
  9 
vote
From project AndroidLabs, under directory /src/com/securitycompass/labs/falsesecuremobile/.
Source RestClient.java
/** 
 * Performs an HTTPS POST with the given data.
 * @param urlString The URL to POST to.
 * @param variables key/value pairs for all parameters to be POSTed.
 * @return The data passed back from the server, as a String.
 * @throws IOException if the network connection failed. 
 * @throws HttpException if the HTTP transaction failed
 */
public String postHttpsContent(String urlString,Map<String,String> variables) throws IOException, HttpException {
  String response="";
  URL url=new URL(urlString);
  HttpsURLConnection httpsConnection=(HttpsURLConnection)url.openConnection();
  if (mHostnameVerifier != null) {
    httpsConnection.setHostnameVerifier(mHostnameVerifier);
  }
  httpsConnection.setDoInput(true);
  httpsConnection.setDoOutput(true);
  httpsConnection.setUseCaches(false);
  httpsConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
  String postData="";
  for (  String key : variables.keySet()) {
    postData+="&" + key + "="+ variables.get(key);
  }
  postData=postData.substring(1);
  DataOutputStream postOut=new DataOutputStream(httpsConnection.getOutputStream());
  postOut.writeBytes(postData);
  postOut.flush();
  postOut.close();
  int responseCode=httpsConnection.getResponseCode();
  if (responseCode == HttpsURLConnection.HTTP_OK) {
    String line;
    BufferedReader br=new BufferedReader(new InputStreamReader(httpsConnection.getInputStream()));
    while ((line=br.readLine()) != null) {
      response+=line;
    }
  }
 else {
    response="";
    Log.e(TAG,"HTTPs request failed on: " + urlString + " With error code: "+ responseCode);
    throw new HttpException(responseCode);
  }
  return response;
}
 

Code Example 3:
  8 
vote
From project andlytics_2, under directory /src/de/betaapps/andlytics/.
Source DeveloperConsole.java
private String getGwtRpcResponse(String developerPostData,URL aURL) throws IOException, ProtocolException {
  String result;
  HttpsURLConnection connection=(HttpsURLConnection)aURL.openConnection();
  connection.setHostnameVerifier(new AllowAllHostnameVerifier());
  connection.setDoOutput(true);
  connection.setDoInput(true);
  connection.setRequestMethod("POST");
  connection.setConnectTimeout(4000);
  connection.setRequestProperty("Host","play.google.com");
  connection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; de; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13");
  connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
  connection.setRequestProperty("Accept-Language","en-us,en;q=0.5");
  connection.setRequestProperty("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
  connection.setRequestProperty("Keep-Alive","115");
  connection.setRequestProperty("Cookie",cookie);
  connection.setRequestProperty("Connection","keep-alive");
  connection.setRequestProperty("Content-Type","text/x-gwt-rpc; charset=utf-8");
  connection.setRequestProperty("X-GWT-Permutation",getGwtPermutation());
  connection.setRequestProperty("X-GWT-Module-Base","https://play.google.com/apps/publish/gwt-play/");
  connection.setRequestProperty("Referer","https://play.google.com/apps/publish/Home");
  OutputStreamWriter streamToAuthorize=new java.io.OutputStreamWriter(connection.getOutputStream());
  streamToAuthorize.write(developerPostData);
  streamToAuthorize.flush();
  streamToAuthorize.close();
  InputStream resultStream=connection.getInputStream();
  BufferedReader aReader=new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
  StringBuffer aResponse=new StringBuffer();
  String aLine=aReader.readLine();
  while (aLine != null) {
    aResponse.append(aLine + "\n");
    aLine=aReader.readLine();
  }
  resultStream.close();
  result=aResponse.toString();
  return result;
}
 

Code Example 4:
  8 
vote
From project android_libcore, under directory /luni/src/test/java/libcore/java/net/.
Source URLConnectionTest.java
public void testConnectViaHttps() throws IOException, InterruptedException {
  TestSSLContext testSSLContext=TestSSLContext.create();
  server.useHttps(testSSLContext.serverContext.getSocketFactory(),false);
  server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
  server.play();
  HttpsURLConnection connection=(HttpsURLConnection)server.getUrl("/foo").openConnection();
  connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
  assertContent("this response comes via HTTPS",connection);
  RecordedRequest request=server.takeRequest();
  assertEquals("GET /foo HTTP/1.1",request.getRequestLine());
}
 

Code Example 5:
  8 
vote
From project android_libcore, under directory /luni/src/test/java/libcore/java/net/.
Source URLConnectionTest.java
public void testConnectViaHttpsWithSSLFallback() throws IOException, InterruptedException {
  TestSSLContext testSSLContext=TestSSLContext.create();
  server.useHttps(testSSLContext.serverContext.getSocketFactory(),false);
  server.enqueue(new MockResponse().setDisconnectAtStart(true));
  server.enqueue(new MockResponse().setBody("this response comes via SSL"));
  server.play();
  HttpsURLConnection connection=(HttpsURLConnection)server.getUrl("/foo").openConnection();
  connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
  assertContent("this response comes via SSL",connection);
  RecordedRequest request=server.takeRequest();
  assertEquals("GET /foo HTTP/1.1",request.getRequestLine());
}
 

Code Example 6:
  8 
vote
From project android_libcore, under directory /luni/src/test/java/libcore/java/net/.
Source URLConnectionTest.java
private void testConnectViaDirectProxyToHttps(ProxyConfig proxyConfig) throws Exception {
  TestSSLContext testSSLContext=TestSSLContext.create();
  server.useHttps(testSSLContext.serverContext.getSocketFactory(),false);
  server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
  server.play();
  URL url=server.getUrl("/foo");
  HttpsURLConnection connection=(HttpsURLConnection)proxyConfig.connect(server,url);
  connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
  assertContent("this response comes via HTTPS",connection);
  RecordedRequest request=server.takeRequest();
  assertEquals("GET /foo HTTP/1.1",request.getRequestLine());
}
 

Code Example 7:
  7 
vote
From project Airports, under directory /src/com/nadmm/airports/notams/.
Source NotamService.java
private void fetchNotams(String icaoCode,File notamFile) throws IOException {
  InputStream in=null;
  String params=String.format(NOTAM_PARAM,icaoCode);
  HttpsURLConnection conn=(HttpsURLConnection)NOTAM_URL.openConnection();
  conn.setRequestProperty("Connection","close");
  conn.setDoInput(true);
  conn.setDoOutput(true);
  conn.setUseCaches(false);
  conn.setConnectTimeout(30 * 1000);
  conn.setReadTimeout(30 * 1000);
  conn.setRequestMethod("POST");
  conn.setRequestProperty("User-Agent","Mozilla/5.0 (X11; U; Linux i686; en-US)");
  conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
  conn.setRequestProperty("Content-Length",Integer.toString(params.length()));
  OutputStream faa=conn.getOutputStream();
  faa.write(params.getBytes("UTF-8"));
  faa.close();
  int response=conn.getResponseCode();
  if (response == HttpURLConnection.HTTP_OK) {
    in=conn.getInputStream();
    ArrayList<String> notams=parseNotamsFromHtml(in);
    in.close();
    BufferedOutputStream cache=new BufferedOutputStream(new FileOutputStream(notamFile));
    for (    String notam : notams) {
      cache.write(notam.getBytes());
      cache.write('\n');
    }
    cache.close();
  }
}
 

Code Example 8:
  7 
vote
From project andlytics, under directory /src/com/github/andlyticsproject/.
Source DeveloperConsole.java
private String getGwtRpcResponse(String developerPostData,URL aURL) throws IOException, ProtocolException, ConnectException {
  String result;
  HttpsURLConnection connection=(HttpsURLConnection)aURL.openConnection();
  connection.setHostnameVerifier(new AllowAllHostnameVerifier());
  connection.setDoOutput(true);
  connection.setDoInput(true);
  connection.setRequestMethod("POST");
  connection.setConnectTimeout(4000);
  connection.setRequestProperty("Host","play.google.com");
  connection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; de; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13");
  connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
  connection.setRequestProperty("Accept-Language","en-us,en;q=0.5");
  connection.setRequestProperty("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
  connection.setRequestProperty("Keep-Alive","115");
  connection.setRequestProperty("Cookie",cookie);
  connection.setRequestProperty("Connection","keep-alive");
  connection.setRequestProperty("Content-Type","text/x-gwt-rpc; charset=utf-8");
  connection.setRequestProperty("X-GWT-Permutation",getGwtPermutation());
  connection.setRequestProperty("X-GWT-Module-Base","https://play.google.com/apps/publish/gwt-play/");
  connection.setRequestProperty("Referer","https://play.google.com/apps/publish/Home");
  OutputStreamWriter streamToAuthorize=new java.io.OutputStreamWriter(connection.getOutputStream());
  streamToAuthorize.write(developerPostData);
  streamToAuthorize.flush();
  streamToAuthorize.close();
  InputStream resultStream=connection.getInputStream();
  BufferedReader aReader=new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
  StringBuffer aResponse=new StringBuffer();
  String aLine=aReader.readLine();
  while (aLine != null) {
    aResponse.append(aLine + "\n");
    aLine=aReader.readLine();
  }
  resultStream.close();
  result=aResponse.toString();
  return result;
}
 

Code Example 9:
  7 
vote
From project andlytics, under directory /src/com/github/andlyticsproject/.
Source DeveloperConsole.java
protected String postUrl(String url,Map<String,String> params) throws IOException {
  String data="";
  for (  String key : params.keySet()) {
    data+="&" + URLEncoder.encode(key,"UTF-8") + "="+ URLEncoder.encode(params.get(key),"UTF-8");
  }
  data=data.substring(1);
  URL aURL=new java.net.URL(url);
  HttpsURLConnection aConnection=(HttpsURLConnection)aURL.openConnection();
  aConnection.setDoOutput(true);
  aConnection.setDoInput(true);
  aConnection.setRequestMethod("POST");
  aConnection.setHostnameVerifier(new AllowAllHostnameVerifier());
  OutputStreamWriter streamToAuthorize=new java.io.OutputStreamWriter(aConnection.getOutputStream());
  streamToAuthorize.write(data);
  streamToAuthorize.flush();
  streamToAuthorize.close();
  InputStream resultStream=aConnection.getInputStream();
  BufferedReader aReader=new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
  StringBuffer aResponse=new StringBuffer();
  String aLine=aReader.readLine();
  while (aLine != null) {
    aResponse.append(aLine + "\n");
    aLine=aReader.readLine();
  }
  resultStream.close();
  return aResponse.toString();
}
 

Code Example 10:
  7 
vote
From project andlytics_2, under directory /src/de/betaapps/andlytics/.
Source DeveloperConsole.java
protected String postUrl(String url,Map<String,String> params) throws IOException {
  String data="";
  for (  String key : params.keySet()) {
    data+="&" + URLEncoder.encode(key,"UTF-8") + "="+ URLEncoder.encode(params.get(key),"UTF-8");
  }
  data=data.substring(1);
  URL aURL=new java.net.URL(url);
  HttpsURLConnection aConnection=(HttpsURLConnection)aURL.openConnection();
  aConnection.setDoOutput(true);
  aConnection.setDoInput(true);
  aConnection.setRequestMethod("POST");
  aConnection.setHostnameVerifier(new AllowAllHostnameVerifier());
  OutputStreamWriter streamToAuthorize=new java.io.OutputStreamWriter(aConnection.getOutputStream());
  streamToAuthorize.write(data);
  streamToAuthorize.flush();
  streamToAuthorize.close();
  InputStream resultStream=aConnection.getInputStream();
  BufferedReader aReader=new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
  StringBuffer aResponse=new StringBuffer();
  String aLine=aReader.readLine();
  while (aLine != null) {
    aResponse.append(aLine + "\n");
    aLine=aReader.readLine();
  }
  resultStream.close();
  return aResponse.toString();
}
 

Code Example 11:
  7 
vote
From project AndroidLabs, under directory /src/com/securitycompass/labs/falsesecuremobile/.
Source RestClient.java
/** 
 * Performs a simple HTTPS GET and returns the result.
 * @param urlName API Service endpoint.
 * @return HttpContent from the url.
 * @throws IOException if the network connection failed.
 */
public String getHttpsContent(String urlName) throws IOException {
  String line;
  String result;
  StringBuilder httpsContent=new StringBuilder();
  URL url=new URL(urlName);
  HttpsURLConnection httpsConnection=(HttpsURLConnection)url.openConnection();
  if (mHostnameVerifier != null) {
    httpsConnection.setHostnameVerifier(mHostnameVerifier);
  }
  int responseCode=httpsConnection.getResponseCode();
  if (responseCode == HttpsURLConnection.HTTP_OK) {
    InputStream inputStream=httpsConnection.getInputStream();
    BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
    while ((line=br.readLine()) != null) {
      httpsContent.append(line);
    }
    httpsConnection.disconnect();
  }
  result=httpsContent.toString();
  return result;
}
 

Code Example 12:
  7 
vote
From project android_libcore, under directory /luni/src/test/java/libcore/java/net/.
Source URLConnectionTest.java
public void testConnectViaHttpsReusingConnections() throws IOException, InterruptedException {
  TestSSLContext testSSLContext=TestSSLContext.create();
  server.useHttps(testSSLContext.serverContext.getSocketFactory(),false);
  server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
  server.enqueue(new MockResponse().setBody("another response via HTTPS"));
  server.play();
  HttpsURLConnection connection=(HttpsURLConnection)server.getUrl("/").openConnection();
  connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
  assertContent("this response comes via HTTPS",connection);
  connection=(HttpsURLConnection)server.getUrl("/").openConnection();
  connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
  assertContent("another response via HTTPS",connection);
  assertEquals(0,server.takeRequest().getSequenceNumber());
  assertEquals(1,server.takeRequest().getSequenceNumber());
}
 

Code Example 13:
  7 
vote
From project android_libcore, under directory /luni/src/test/java/libcore/java/net/.
Source URLConnectionTest.java
public void testConnectViaHttpsReusingConnectionsDifferentFactories() throws IOException, InterruptedException {
  TestSSLContext testSSLContext=TestSSLContext.create();
  server.useHttps(testSSLContext.serverContext.getSocketFactory(),false);
  server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
  server.enqueue(new MockResponse().setBody("another response via HTTPS"));
  server.play();
  HttpsURLConnection connection=(HttpsURLConnection)server.getUrl("/").openConnection();
  connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
  assertContent("this response comes via HTTPS",connection);
  connection=(HttpsURLConnection)server.getUrl("/").openConnection();
  try {
    readAscii(connection.getInputStream(),Integer.MAX_VALUE);
    fail("without an SSL socket factory, the connection should fail");
  }
 catch (  SSLException expected) {
  }
}
 

Code Example 14:
  7 
vote
From project android_libcore, under directory /luni/src/test/java/libcore/java/net/.
Source URLConnectionTest.java
/** 
 * Verify that we don't retry connections on certificate verification errors. http://code.google.com/p/android/issues/detail?id=13178
 */
public void testConnectViaHttpsToUntrustedServer() throws IOException, InterruptedException {
  TestSSLContext testSSLContext=TestSSLContext.create(TestKeyStore.getClientCA2(),TestKeyStore.getServer());
  server.useHttps(testSSLContext.serverContext.getSocketFactory(),false);
  server.enqueue(new MockResponse());
  server.play();
  HttpsURLConnection connection=(HttpsURLConnection)server.getUrl("/foo").openConnection();
  connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
  try {
    connection.getInputStream();
    fail();
  }
 catch (  SSLHandshakeException expected) {
    assertTrue(expected.getCause() instanceof CertificateException);
  }
  assertEquals(0,server.getRequestCount());
}
 

Code Example 15:
  7 
vote
From project android_libcore, under directory /luni/src/test/java/libcore/java/net/.
Source URLConnectionTest.java
/** 
 * We were verifying the wrong hostname when connecting to an HTTPS site through a proxy. http://b/3097277
 */
private void testConnectViaHttpProxyToHttps(ProxyConfig proxyConfig) throws Exception {
  TestSSLContext testSSLContext=TestSSLContext.create();
  RecordingHostnameVerifier hostnameVerifier=new RecordingHostnameVerifier();
  server.useHttps(testSSLContext.serverContext.getSocketFactory(),true);
  server.enqueue(new MockResponse().clearHeaders());
  server.enqueue(new MockResponse().setBody("this response comes via a secure proxy"));
  server.play();
  URL url=new URL("https://android.com/foo");
  HttpsURLConnection connection=(HttpsURLConnection)proxyConfig.connect(server,url);
  connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
  connection.setHostnameVerifier(hostnameVerifier);
  assertContent("this response comes via a secure proxy",connection);
  RecordedRequest connect=server.takeRequest();
  assertEquals("Connect line failure on proxy","CONNECT android.com:443 HTTP/1.1",connect.getRequestLine());
  assertContains(connect.getHeaders(),"Host: android.com");
  RecordedRequest get=server.takeRequest();
  assertEquals("GET /foo HTTP/1.1",get.getRequestLine());
  assertContains(get.getHeaders(),"Host: android.com");
  assertEquals(Arrays.asList("verify android.com"),hostnameVerifier.calls);
}
 

Code Example 16:
  7 
vote
From project android_libcore, under directory /luni/src/test/java/libcore/java/net/.
Source URLConnectionTest.java
/** 
 * Test which headers are sent unencrypted to the HTTP proxy.
 */
public void testProxyConnectIncludesProxyHeadersOnly() throws IOException, InterruptedException {
  RecordingHostnameVerifier hostnameVerifier=new RecordingHostnameVerifier();
  TestSSLContext testSSLContext=TestSSLContext.create();
  server.useHttps(testSSLContext.serverContext.getSocketFactory(),true);
  server.enqueue(new MockResponse().clearHeaders());
  server.enqueue(new MockResponse().setBody("encrypted response from the origin server"));
  server.play();
  URL url=new URL("https://android.com/foo");
  HttpsURLConnection connection=(HttpsURLConnection)url.openConnection(server.toProxyAddress());
  connection.addRequestProperty("Private","Secret");
  connection.addRequestProperty("Proxy-Authorization","bar");
  connection.addRequestProperty("User-Agent","baz");
  connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
  connection.setHostnameVerifier(hostnameVerifier);
  assertContent("encrypted response from the origin server",connection);
  RecordedRequest connect=server.takeRequest();
  assertContainsNoneMatching(connect.getHeaders(),"Private.*");
  assertContains(connect.getHeaders(),"Proxy-Authorization: bar");
  assertContains(connect.getHeaders(),"User-Agent: baz");
  assertContains(connect.getHeaders(),"Host: android.com");
  assertContains(connect.getHeaders(),"Proxy-Connection: Keep-Alive");
  RecordedRequest get=server.takeRequest();
  assertContains(get.getHeaders(),"Private: Secret");
  assertEquals(Arrays.asList("verify android.com"),hostnameVerifier.calls);
}
 

Code Example 17:
  7 
vote
From project android_libcore, under directory /luni/src/test/java/libcore/java/net/.
Source URLConnectionTest.java
public void testRedirectedOnHttps() throws IOException, InterruptedException {
  TestSSLContext testSSLContext=TestSSLContext.create();
  server.useHttps(testSSLContext.serverContext.getSocketFactory(),false);
  server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP).addHeader("Location: /foo").setBody("This page has moved!"));
  server.enqueue(new MockResponse().setBody("This is the new location!"));
  server.play();
  HttpsURLConnection connection=(HttpsURLConnection)server.getUrl("/").openConnection();
  connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
  assertEquals("This is the new location!",readAscii(connection.getInputStream(),Integer.MAX_VALUE));
  RecordedRequest first=server.takeRequest();
  assertEquals("GET / HTTP/1.1",first.getRequestLine());
  RecordedRequest retry=server.takeRequest();
  assertEquals("GET /foo HTTP/1.1",retry.getRequestLine());
  assertEquals("Expected connection reuse",1,retry.getSequenceNumber());
}
 

Code Example 18:
  5 
vote
From project Android-Custom-Gallery-And-Instant-Upload, under directory /src/com/isummation/customgallery/.
Source UploadQueue.java
private void trustAllHosts(){
  TrustManager[] trustAllCerts=new TrustManager[]{new X509TrustManager(){
    public java.security.cert.X509Certificate[] getAcceptedIssuers(){
      return new java.security.cert.X509Certificate[]{};
    }
    public void checkClientTrusted(    X509Certificate[] chain,    String authType) throws CertificateException {
    }
    public void checkServerTrusted(    X509Certificate[] chain,    String authType) throws CertificateException {
    }
  }
};
  try {
    defaultSSLSocketFactory=HttpsURLConnection.getDefaultSSLSocketFactory();
    SSLContext sc=SSLContext.getInstance("TLS");
    sc.init(null,trustAllCerts,new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Code Example 19:
  5 
vote
From project android-sdk_1, under directory /src/com/appota/payment/.
Source AppotaClient.java
/** 
 * Trust every server - dont check for any certificate
 */
private static void trustAllHosts(){
  TrustManager[] trustAllCerts=new TrustManager[]{new X509TrustManager(){
    @Override public void checkClientTrusted(    java.security.cert.X509Certificate[] chain,    String authType) throws java.security.cert.CertificateException {
    }
    @Override public void checkServerTrusted(    java.security.cert.X509Certificate[] chain,    String authType) throws java.security.cert.CertificateException {
    }
    @Override public java.security.cert.X509Certificate[] getAcceptedIssuers(){
      return null;
    }
  }
};
  try {
    SSLContext sc=SSLContext.getInstance("TLS");
    sc.init(null,trustAllCerts,new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Code Example 20:
  5 
vote
From project AndroidLabs, under directory /src/com/securitycompass/labs/falsesecuremobile/.
Source RestClient.java
/** 
 * Sets the application to accept all SSL certificates.
 * @throws NoSuchAlgorithmException if the SSL encryption algorithm wasn't available.
 * @throws KeyManagementException if initialising ther SSLContext fails. 
 */
private void setLaxSSL() throws NoSuchAlgorithmException, KeyManagementException {
  TrustManager[] trustAllCerts=new TrustManager[]{new X509TrustManager(){
    @Override public X509Certificate[] getAcceptedIssuers(){
      return null;
    }
    @Override public void checkServerTrusted(    X509Certificate[] chain,    String authType) throws CertificateException {
    }
    @Override public void checkClientTrusted(    X509Certificate[] chain,    String authType) throws CertificateException {
    }
  }
};
  SSLContext sslContext=SSLContext.getInstance("TLS");
  sslContext.init(null,trustAllCerts,new java.security.SecureRandom());
  HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
  mHostnameVerifier=new AllowAllHostnameVerifier();
}
 

Code Example 21:
  5 
vote
From project android_4, under directory /appMobiLib/src/com/phonegap/.
Source FileTransfer.java
/** 
 * This function will install a trust manager that will blindly trust all SSL  certificates.  The reason this code is being added is to enable developers  to do development using self signed SSL certificates on their web server. The standard HttpsURLConnection class will throw an exception on self  signed certificates if this code is not run.
 */
private void trustAllHosts(){
  TrustManager[] trustAllCerts=new TrustManager[]{new X509TrustManager(){
    public java.security.cert.X509Certificate[] getAcceptedIssuers(){
      return new java.security.cert.X509Certificate[]{};
    }
    public void checkClientTrusted(    X509Certificate[] chain,    String authType) throws CertificateException {
    }
    public void checkServerTrusted(    X509Certificate[] chain,    String authType) throws CertificateException {
    }
  }
};
  try {
    defaultSSLSocketFactory=HttpsURLConnection.getDefaultSSLSocketFactory();
    SSLContext sc=SSLContext.getInstance("TLS");
    sc.init(null,trustAllCerts,new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  }
 catch (  Exception e) {
    Log.e(LOG_TAG,e.getMessage(),e);
  }
}
 

Comments

Popular posts from this blog

Custom camera using SurfaceView android with autofocus & auto lights & more

Custom camera using SurfaceView android with autofocus & auto lights & much more /**  * @author Tatyabhau Chavan  *  */ public class Preview extends SurfaceView implements SurfaceHolder.Callback {     private SurfaceHolder mHolder;     private Camera mCamera;     public Camera.Parameters mParameters;     private byte[] mBuffer;     private Activity mActivity;     // this constructor used when requested as an XML resource     public Preview(Context context, AttributeSet attrs) {         super(context, attrs);         init();     }     public Preview(Context context) {         super(context);         init();     }     public Camera getCamera() {         return this.mCamera;     }     public void init() {         // Install a SurfaceHolder.Callback so we get notified when the         // underlying surface is created and destroyed.         mHolder = getHolder();         mHolder.addCallback(this);         mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);     }     public

Get Android phone call history/log programmatically

Get Android phone call history/log programmatically To get call history programmatically first add read conact permission in Manifest file : <uses-permission android:name="android.permission.READ_CONTACTS" /> Create xml file. Add the below code in xml file : <Linearlayout android:layout_height="fill_parent"  android:layout_width="fill_parent" android:orientation="vertical"> <Textview android:id="@+id/call" android:layout_height="fill_parent" android:layout_width="fill_parent"> </Textview> </Linearlayout> Now call the getCallDetails() method in java class : private void getCallDetails() { StringBuffer sb = new StringBuffer(); Cursor managedCursor = managedQuery( CallLog.Calls.CONTENT_URI,null, null,null, null); int number = managedCursor.getColumnIndex( CallLog.Calls.NUMBER ); int type = managedCursor.getColumnIndex( CallLog.Calls.TYPE ); int date = managedCur

Bitmap scalling and cropping from center

How to Bitmap scalling and cropping from center? public class ScalingUtilities {     /**      * Utility function for decoding an image resource. The decoded bitmap will      * be optimized for further scaling to the requested destination dimensions      * and scaling logic.      *      * @param res      *            The resources object containing the image data      * @param resId      *            The resource id of the image data      * @param dstWidth      *            Width of destination area      * @param dstHeight      *            Height of destination area      * @param scalingLogic      *            Logic to use to avoid image stretching      * @return Decoded bitmap      */     public static Bitmap decodeResource(Resources res, int resId, int dstWidth,             int dstHeight, ScalingLogic scalingLogic) {         Options options = new Options();         options.inJustDecodeBounds = true;         BitmapFactory.decodeResource(res, resId, options);