HttpsURLConnection Secure transmission (HTTPS-Secure Hypertext Transfer Protocol)

Source: Internet
Author: User

HttpsURLConnection extends HttpURLConnection and supports various https-specific functions. This class uses HostnameVerifier and SSLSocketFactory. The default implementation is defined for both classes. However, you can replace this implementation with each class (static) or each instance. All new httpsurlconnections
When an instance is created, it will be assigned a "default" static value. You can override these values by calling the appropriate set method for each instance before the connection.

Adding https: // prefix before the URL indicates that SSL encryption is used. It is safer to transmit and receive information between your computer and the server.

To enable SSL for a Web server, you need to obtain a server certificate and bind the certificate to the server that uses SSL.
Http and https use completely different connection methods, with different ports. The former is 80, and the latter is 443. The http connection is simple and stateless ,...

HTTPS is a network protocol built by SSL + HTTP for encrypted transmission and identity authentication.
More secure than http

Package com. yixun. WAP;

Import java. Io .*;
Import java.net .*;
Import java. Security .*;
Import java. Security. cert .*;
Import javax.net. SSL .*;

Public class httpsurlconnectiontest {

Private string url = "https://esales.the9.com/esa/DealerLogin.php? Txt_slogin = andysmile234 & pas_spwd = 343211 & userstatus = 1 ";

Private myx509trustmanager xtm = new myx509trustmanager ();

Private myhostnameverifier hnv = new myhostnameverifier ();

Public httpsurlconnectiontest (){
Sslcontext = NULL;
Try {
SslContext = SSLContext. getInstance ("TLS"); // or SSL
X509TrustManager [] xtmArray = new X509TrustManager [] {xtm };
SslContext. init (null, xtmArray, new java. security. SecureRandom ());
} Catch (GeneralSecurityException e ){
E. printStackTrace ();
}
If (sslContext! = Null ){
HttpsURLConnection. setDefaultSSLSocketFactory (sslContext. getSocketFactory ());
}
HttpsURLConnection. setDefaultHostnameVerifier (hnv );
}

Public void run (){
HttpsURLConnection urlCon = null;
Try {
UrlCon = (HttpsURLConnection) (new URL (url). openConnection ();
UrlCon. setDoOutput (true );
UrlCon. setRequestMethod ("POST ");
URL con. setRequestProperty ("Content-Length", "1024 ");
UrlCon. setUseCaches (false );
UrlCon. setDoInput (true );
UrlCon. getOutputStream (). write ("request content". getBytes ("gbk "));
UrlCon. getOutputStream (). flush ();
UrlCon. getOutputStream (). close ();
BufferedReader in = new BufferedReader (new InputStreamReader (urlCon. getInputStream ()));
String line;
While (line = in. readLine ())! = Null ){
System. out. println (line );
}
// Add your own code
} Catch (MalformedURLException e ){
E. printstacktrace ();
} Catch (ioexception e ){
E. printstacktrace ();
} Catch (exception e ){
E. printstacktrace ();
}
}

Public static void main (string [] ARGs ){
Httpsurlconnectiontest httpstest = new httpsurlconnectiontest ();
Httpstest. Run ();
}
}

/**
* Rewrite the three methods.
* @ Author Administrator
*
*/
Class myx509trustmanager implements x509trustmanager {

Public void checkclienttrusted (x509certificate [] Chain, string authtype ){
}

Public void checkservertrusted (x509certificate [] Chain, string authtype ){
System. Out. println ("Cert:" + chain [0]. tostring () + ", authtype:" + authtype );
}

Public x509certificate [] getacceptedissuers (){
Return NULL;
}
}

/**
* Rewrite a method.
* @ Author Administrator
*
*/
Class myhostnameverifier implements hostnameverifier {

Public Boolean verify (string hostname, sslsession session ){
System. Out. println ("Warning: url host:" + hostname + "vs." + session. getpeerhost ());
Return true;
}
}

From: http://www.zimbio.com/member/kinggod03/articles/HImNQwJm-Lp/
Finally, the blog backup program is completed. I am confident that I can tell other companies my account and ask them to back up my account. I had nothing to worry about. I also tried to let my cool and soft hands experience the feeling of coding, and completed the program of backing up the blog. There are more than 300 lines in total, and the function is actually very simple, that is, to save the webpage of each article, but for the first time to do this kind of network program, many of them need to learn. The following are some tips:
1. the SSL protocol is required for login. It seems that the encapsulation is too good-just bake the code, which is very simple and I don't understand what it means now.
2. Use cookies. It takes a long time to save the SessionID after logging on. Use IE to log on and set the Cookie as a "prompt", so all the dark box operations will see the sun. At this time, we know that almost every web page uses cookies to store things, and there is still privacy. Baidu must use cookies, otherwise it will not be able to log on. This is too much, so we should provide a choice. After obtaining the Cookie value, remove "PASSPORTRETRYSTRING = deleted;". This field should be used to prevent repeated submission. If this parameter is not removed, no logon is performed. The removed Cookie values (mainly BDUUSS and BDUID) can be sent to the server, so that you can view the blog as a login user.
3. HTML code can be processed in XML format. However, without patience, I can use a string to replace search. This is inefficient and can be improved.
4. Connecting that part of the Code draws on the source code accessed by the blog provided by Google, which has benefited a lot. Baidu does not have an API, or I will not have to worry about it.
5. There are still many details, such as reading and writing files.
6. Look at the HTML code !!!
In order to gain trust, I will post the source code, which is why I don't want to use commercial software. Commercial software is the most important thing to make money. He doesn't trust me, and I don't trust him either. However, I just want to express my peace of mind and convenience. Package com. yixun. wap;

/**
* This program can be used to back up articles in Baidu space.
* 18 hours costed.
* Niuys.
* 2007.7.11
*/
Import java. io .*;
Import java.net .*;
Import java. Security. generalsecurityexception;
Import java. Security. cert. x509certificate;
Import java. util .*;

Import javax.net. SSL. hostnameverifier;
Import javax.net. SSL. httpsurlconnection;
Import javax.net. SSL. sslcontext;
Import javax.net. SSL. sslsession;
Import javax.net. SSL. x509trustmanager;

Public class opticalbackup {
// Encode the blog Information
Private string urlstring = "https://passport.baidu.com /? Login ";

// Saved directory
Private string savedir = "L: \ blogbackup ";

// Blog root path
Private string spaceroot = "http://hi.baidu.com/niuys/blog/index ";

Private string articleurlhead = "/niuys/blog/item /";

// Parameters needed to log in.
Map parameters = new hashmap ();

// Use the sessionid provided by Cookie to establish a connection.
String cookieval = NULL;

// Create an anonymous class to trust all certificates.
// This is bad style, you should create a separate class.
Private x509trustmanager xtm = new x509trustmanager (){
Public void checkClientTrusted (X509Certificate [] chain, String authType ){
}

Public void checkServerTrusted (X509Certificate [] chain, String authType ){
// System. out. println ("cert:" + chain [0]. toString () + ", authType:
//"
// + AuthType );
}

Public X509Certificate [] getAcceptedIssuers (){
Return NULL;
}
};

// Create an class to trust all hosts
Private hostnameverifier hnv = new hostnameverifier (){
Public Boolean verify (string hostname, sslsession session ){
// System. Out. println ("hostname:" + hostname );
Return true;
}
};

// In this function we configure our system with a less stringent
// Hostname verifier and X509 trust manager. This code is
// Executed once, and callthe static methods of HttpsURLConnection
Public OpticalBackup (){
// The parameters needed to log on.
Parameters. put ("username", "confidential ");
Parameters. put ("password", "confidential ");
Parameters. put ("Submit", "login ");
Parameters. put ("tpl", "sp ");
Parameters. put ("tpl_reg", "sp ");
Parameters. put ("u", "http://www.baidu.com /");

// Check the saveDir
File dir = new File (saveDir );
If (! Dir. exists ()){
Dir. mkdir ();
}

// Initialize the TLS SSLContext
// Our TrustManager
SSLContext sslContext = null;
Try {
SslContext = SSLContext. getInstance ("TLS ");

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.