Java access to the implementation of HTTPS, multithreading, write log

Source: Internet
Author: User
Tags static class


Package ivrinter;



Import Java.io.BufferedReader;
Import Java.io.BufferedWriter;
Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.FileWriter;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.net.Authenticator;
Import java.net.PasswordAuthentication;
Import Java.net.URL;
Import java.security.KeyManagementException;
Import java.security.NoSuchAlgorithmException;
Import java.security.cert.CertificateException;
Import Java.security.cert.X509Certificate;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;



Import Javax.net.ssl.HostnameVerifier;
Import javax.net.ssl.HttpsURLConnection;
Import Javax.net.ssl.SSLContext;
Import javax.net.ssl.SSLSession;
Import Javax.net.ssl.TrustManager;
Import Javax.net.ssl.X509TrustManager;



Java Interface for IVR invocation
public class Copyofmyhttps {
public static int seq=0;
public static int maxnum=10; It's a log file, 0-9.
public static int maxlength=1024*10240;//file length 10M
public static int ttt=10000;



public synchronized static int Requesthttps (Pojo p,string url,string proxy,int port,final String username,
Final String password) throws Keymanagementexception, IOException {//synchronized Avoid multithreaded access to files, exceptions
Record log
String logstr= "<1>url:" +getstring (URL) + "proxy:" +getstring (proxy)
+ "PORT:" +port+ "username:" +username+ "Password:" +getstring (password) + "/n";
WriteToFile2 (LOGSTR);



System.out.println ("1 amount >>" + TTT);
ttt-=10;
System.out.println ("2 surplus >>" + TTT);
Judging input parameters
if (Url.length () >1024) return 1;
if (Proxy.length () >1024) return 2;




Boolean proxyflag= false;
if (!) ( Proxy = = NULL | | "". Equals (proxy)) {//proxy
Initproxy (proxy,port,username,password);
proxyflag= true;
}
Sslcontext sc = null;
try {
sc = sslcontext.getinstance (' SSL ');
' catch (nosuchalgorithmexception e) {
E.printstacktrace ();
}
//Specify trusted HTTPS
Sc.init (null, New Trustmanager[]{new Trustanytrustmanager ()}, New Java.security.SecureRandom ());
URL console = new URL (URL);



Record log
Logstr= "<2>url:" +getstring (URL) + "proxy:" +getstring (proxy)
+ "PORT:" +port+ "username:" +username+ "Password:" +getstring (password) + "/n";
WriteToFile2 (LOGSTR);

Httpsurlconnection conn = (httpsurlconnection) console.openconnection ();
Conn.setsslsocketfactory (Sc.getsocketfactory ());
Conn.sethostnameverifier (New Trustanyhostnameverifier ());
String mes= "";
try {
Mes = Conn.getresponsemessage ();
SYSTEM.OUT.PRINTLN ("Return result:" +mes);
catch (Exception e) {
return 3;
}
if (! () Ok ". Equals (MES))) {
if (Proxyflag) {
Return 4;//HTTPS address and proxy information is correct
}else{
Return 5;//HTTPS address is correct
}
}
Conn.connect ();



Record log
Logstr= "<3>url:" +getstring (URL) + "proxy:" +getstring (proxy)
+ "PORT:" +port+ "username:" +username+ "Password:" +getstring (password) + "/n";
WriteToFile2 (LOGSTR);




InputStream is = Conn.getinputstream ();
BufferedReader reader = new BufferedReader (new InputStreamReader (IS));
String curline= "";
String contend= "";
while ((CurLine = Reader.readline ())!= null) {
Contend+=curline;
System.out.println (CurLine);
}
P.res = contend;
Is.close ();




Record log
Logstr= "<4>httpreturn:" + getString (p.res) + "URL:" +getstring (URL) + "proxy:" +getstring (proxy)
+ "PORT:" +port+ "username:" +username+ "Password:" +getstring (password) + "/n";
WriteToFile2 (LOGSTR);




SimpleDateFormat sf=new SimpleDateFormat ("HH:mm:ss");
System.out.println (New Date ()) (Sf.format);



if (Conn.getresponsecode () ==200) {
return 0;
}else{
if (Proxyflag) {
return 6;
}else{
return 7;
}
}
}


Write a file
public static void WriteToFile (File file,string str) {
BufferedWriter Pw=null;
try {
Pw=new BufferedWriter (New FileWriter (File.getabsolutepath (), true);
Pw.write (str);
catch (FileNotFoundException e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
}finally{
try {
Pw.flush ();
Pw.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
}
public static string getString (String str) {
if (Str.length () >6) {
Return str.substring (0,4) + "*" +str.substring (Str.length ()-2);
}
return str;
}
Write file (decide whether to switch)
The path is to be perfected by adding an input parameter TODO ...
public static void WriteToFile2 (String str) {
File File = new file ("Hwhttp_301_" +seq+ ". Log");
if (File.length () +str.getbytes (). length > MaxLength) {
seq++;
if (seq >= maxnum) {
seq = 0;
}
File = new file ("Hwhttp_301_" +seq+ ". Log");
if (file.exists ()) {
File.delete ();
File = new file ("Hwhttp_301_" +seq+ ". Log");
}
}
WriteToFile (FILE,STR);
}

Initialize Agent
public static void Initproxy (string host, int port, final String username,
Final String password) {
Authenticator.setdefault (New Authenticator () {
Protected Passwordauthentication getpasswordauthentication () {
Return to New Passwordauthentication (username,
New String (password). ToCharArray ());
}
});
System.setproperty ("Proxytype", "4");
System.setproperty ("ProxyPort", integer.tostring (port));
System.setproperty ("ProxyHost", host);
System.setproperty ("Proxyset", "true");
}
private static class Trustanytrustmanager implements X509trustmanager {
public void checkclienttrusted (x509certificate[] chain, String authtype) throws Certificateexception {
}
public void checkservertrusted (x509certificate[] chain, String authtype) throws Certificateexception {
}
Public x509certificate[] Getacceptedissuers () {
return new x509certificate[]{};
}
}
private static class Trustanyhostnameverifier implements Hostnameverifier {
public boolean verify (String hostname, sslsession session) {
return true;
}
}
}
Class pojo{
String Res;
}





--------------------------------------------------------------------------------------------------------------- -



Test class:



Package ivrinter;



Import java.io.IOException;
Import java.security.KeyManagementException;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;



public class Test extends thread{
public static Pojo p=new Pojo ();

@Override
public void Run () {
try {
int a=new Myhttps (). Requesthttps (P, "https://www.mpower-shipper.com/MPS/Home.jsp", 8080, NULL, NULL);
catch (Keymanagementexception e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
}


}



public static void Main (string[] args) throws exception{



SimpleDateFormat sf=new SimpleDateFormat ("HH:mm:ss");
System.out.println (New Date ()) (Sf.format);
for (int i=0;i<10000;i++) {
New Test (). Start ();
}
}



}









 


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.