HttpPut Multi-part and handle https request.

Source

< project  xmlns ="http://maven.apache.org/POM/4.0.0"  xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" package com.karl.learn;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.http.HttpException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
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.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;

public  class HTTPClient {
     private  static String TrustKeyStore = "/opt/ericsson/jboss_trust.keystore";
     private  static String TrustKeyPass = "pass";
     private  static SSLSocketFactory trustFactory =  null;
     private  static  final String KEY = "jaas is the way";
     private  static  int timeout = 60;
     private  static  final String boundary = "frontier";
     private  static String contentType = "multipart/mixed; boundary=\""
            + boundary + "\"";
     private  static  final String lineEnd = "\r\n";
     private  static  final String twoHyphens = "--";

     public  static  boolean HttpPut(String uri, String requestBody, File file)
             throws HttpException, FileNotFoundException, IOException {
         boolean httpsFlag = uri.toLowerCase().startsWith("https");
        HttpClient client = getDefaultHttpClient(httpsFlag, timeout);
        HttpPut method =  new HttpPut(uri);
        method.addHeader("Content-Type", contentType);
         int maxBufferSize = 100 * 1024;
        InputStreamEntity body = buildAddContentBody(requestBody, file,
                maxBufferSize);
        method.setEntity(body);
         int resp = client.execute(method).getStatusLine().getStatusCode();
        client.getConnectionManager().shutdown();
         if (resp >= 200 && resp < 300) {
             return  true;
        }  else {
             return  false;
        }
    }

     private  static InputStreamEntity buildAddContentBody(String requestBody,
            File file,  int maxBufferSize)  throws IOException,
            FileNotFoundException {
         int bytesRead;
         int bytesAvailable;
         int bufferSize;
        OutputStream os =  new ByteArrayOutputStream();

        StringBuilder builder =  new StringBuilder(200);
        builder.append(twoHyphens + boundary + lineEnd);
        builder.append("Content-Type: application/xml");
        builder.append(lineEnd + lineEnd);
        builder.append(requestBody);
        builder.append(lineEnd + twoHyphens + boundary + lineEnd);
        builder.append("Content-Type: application/octet-stream");
        builder.append(lineEnd + lineEnd);

        os.write(builder.toString().getBytes());

        FileInputStream fileInputStream =  new FileInputStream(file);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
         byte[] bufferFile =  new  byte[bufferSize];

        bytesRead = fileInputStream.read(bufferFile, 0, bufferSize);
         while (bytesRead > 0) {
            os.write(bufferFile, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(bufferFile, 0, bufferSize);
        }
        os.write(lineEnd.getBytes());
        os.write((twoHyphens + boundary + twoHyphens + lineEnd).getBytes());
        fileInputStream.close();

         byte[] inBuffer =  new  byte[maxBufferSize];
        os.write(inBuffer);
        InputStream is =  new ByteArrayInputStream(inBuffer);
         return  new InputStreamEntity(is, -1);

    }

     private  static String decode(String secret) {
         try {
             byte[] kbytes = KEY.getBytes();
            SecretKeySpec key =  new SecretKeySpec(kbytes, "Blowfish");

            BigInteger n =  new BigInteger(secret, 16);
             byte[] encoding = n.toByteArray();

             if (encoding.length % 8 != 0) {
                 int length = encoding.length;
                 int newLength = (length / 8 + 1) * 8;
                 int pad = newLength - length;
                 byte[] old = encoding;
                encoding =  new  byte[newLength];
                 for ( int i = old.length - 1; i >= 0; --i) {
                    encoding[(i + pad)] = old[i];
                }
            }

            Cipher cipher = Cipher.getInstance("Blowfish");
            cipher.init(2, key);
             byte[] decode = cipher.doFinal(encoding);
             return  new String(decode);
        }  catch (Exception e) {
             return secret;
        }
    }

     private  static KeyStore loadKeyStore(String path, String passwd) {
        KeyStore keyStore =  null;
        FileInputStream keyStoreIn =  null;
         try {
            keyStoreIn =  new FileInputStream( new File(path));
        }  catch (FileNotFoundException e) {
            System.out.println("Failed to open keystore: " + e.toString());
             return  null;
        }

         try {
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(keyStoreIn, decode(passwd).toCharArray());
        }  catch (KeyStoreException e) {
            System.out.println("Failed to declare keystore: " + e.toString());
        }  catch (NoSuchAlgorithmException e) {
            System.out.println("Failed to load keystore: " + e.toString());
            ;
        }  catch (CertificateException e) {
            System.out.println("Failed to load keystore: " + e.toString());
        }  catch (IOException e) {
            System.out.println("Failed to load keystore: " + e.toString());
        }  finally {
             try {
                keyStoreIn.close();
            }  catch (IOException e) {
                System.out.println("Failed to close keystore: " + e.toString());
            }
        }

         return keyStore;
    }

     public  static SSLSocketFactory getTrustSSLSocketFactory(String tsPath,
            String tsPass) {
         if (tsPath ==  null || tsPass ==  null) {
            System.out
                    .println("Failed to create SSLSocketFactory due to truststore path is null ");
             return  null;
        }

         if (trustFactory ==  null || tsPath.equalsIgnoreCase(tsPath)
                || tsPass.equalsIgnoreCase(tsPass)) {
            KeyStore localTrustStore = loadKeyStore(tsPath, tsPass);
             if (localTrustStore ==  null) {
                System.out
                        .println("Failed to create SSLSocketFactory due to keystore is null ");
                 return  null;
            }

             try {
                trustFactory =  new SSLSocketFactory(localTrustStore);
            }  catch (KeyManagementException e) {
                System.out.println("Failed to create SSLSocketFactory: "
                        + e.toString());
            }  catch (UnrecoverableKeyException e) {
                System.out.println("Failed to create SSLSocketFactory: "
                        + e.toString());
            }  catch (NoSuchAlgorithmException e) {
                System.out.println("Failed to create SSLSocketFactory: "
                        + e.toString());
            }  catch (KeyStoreException e) {
                System.out.println("Failed to create SSLSocketFactory: "
                        + e.toString());
            }
        }

         return trustFactory;
    }

     public  static HttpClient getDefaultHttpClient( boolean httpsFlag,
             int timeoutInSecond)  throws HttpException {

        HttpParams params =  new BasicHttpParams();
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                timeoutInSecond * 1000);
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT,
                timeoutInSecond * 1000);

        SchemeRegistry schemeR =  new SchemeRegistry();

        schemeR.register( new Scheme("http", 80, PlainSocketFactory
                .getSocketFactory()));
         if (httpsFlag) {
            SSLSocketFactory sslFactory = getTrustSSLSocketFactory(
                    TrustKeyPass, TrustKeyStore);
             if (sslFactory ==  null) {

                 throw  new HttpException("SSL Factory class is null");
            }
            schemeR.register( new Scheme("https", 8443, sslFactory));
        }

        PoolingClientConnectionManager pccm =  new PoolingClientConnectionManager(
                schemeR);

        DefaultHttpClient client =  new DefaultHttpClient(pccm, params);

        DefaultHttpRequestRetryHandler retryHandler =  new DefaultHttpRequestRetryHandler(
                0,  false);
        client.setHttpRequestRetryHandler(retryHandler);

         return client;
    }
}

pom.xml

< project  xmlns ="http://maven.apache.org/POM/4.0.0"  xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation ="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >
     < modelVersion >4.0.0 </ modelVersion >

     < groupId >com.karl.learn </ groupId >
     < artifactId >TestProject </ artifactId >
     < version >1.0 </ version >
     < packaging >jar </ packaging >

     < name >TestProject </ name >
     < url >http://maven.apache.org </ url >

     < properties >
         < project.build.sourceEncoding >UTF-8 </ project.build.sourceEncoding >
     </ properties >

     < dependencies >
         < dependency >
             < groupId >junit </ groupId >
             < artifactId >junit </ artifactId >
             < version >4.8.2 </ version >
             < scope >test </ scope >
         </ dependency >
         < dependency >
             < groupId >org.apache.httpcomponents </ groupId >
             < artifactId >httpclient </ artifactId >
             < version >4.2.1 </ version >
             < scope >compile </ scope >
         </ dependency >
     </ dependencies >
</ project >

 

 

你可能感兴趣的:(request)