顯示具有 [Java 代碼範本] 標籤的文章。 顯示所有文章
顯示具有 [Java 代碼範本] 標籤的文章。 顯示所有文章

2017年4月29日 星期六

[ Java 代碼範本 ] HttpClient4.x: Making HTTPS call using Apache HttpClient

Source From Here 
Preface 
This post details about making Secure HTTP (HTTPs) call from a server using Apache HTTPClient library

Trust any certificate approach (Simple, not recommended for production code.
The simplest will be to ignore the ssl certificates and to trust any connection. This approach is not acceptable for production code as it defeat the purpose of using HTTPS. However in some use cases if you want to try out something quickly you can go with this route. 
  1. import javax.net.ssl.SSLContext;  
  2. import javax.net.ssl.X509TrustManager;  
  3.   
  4. import org.apache.http.client.HttpClient;  
  5. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;  
  6. import org.apache.http.conn.ssl.SSLContexts;  
  7.   
  8. import org.apache.http.impl.client.CloseableHttpClient;  
  9. import org.apache.http.impl.client.HttpClients;  
  10.   
  11. import java.security.SecureRandom;  
  12.   
  13. public class HttpClientFactory {  
  14.   
  15.     private static CloseableHttpClient client;  
  16.   
  17.     public static HttpClient getHttpsClient() throws Exception {  
  18.   
  19.         if (client != null) {  
  20.             return client;  
  21.         }  
  22.         SSLContext sslcontext = SSLContexts.custom().useSSL().build();  
  23.         sslcontext.init(nullnew X509TrustManager[]{new HttpsTrustManager()}, new SecureRandom());  
  24.         SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,  
  25.                 SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);  
  26.         client = HttpClients.custom().setSSLSocketFactory(factory).build();  
  27.   
  28.         return client;  
  29.     }  
  30.   
  31.     public static void releaseInstance() {  
  32.         client = null;  
  33.     }  
  34. }  
The above method will return httpClient object which can be used to make any HTTPS calls. Performing HTTPS call is no different from making HTTP call from now on. So you can have a factory with two methods, one for secure and one for non-secure. Here we have used HttpsTrustManager, which will do nothing more than trusing all clients. This is done by simply implementing X509TrustManager and auto generating all the methods. 
  1. import java.security.cert.CertificateException;  
  2. import java.security.cert.X509Certificate;  
  3.   
  4. import javax.net.ssl.X509TrustManager;  
  5.   
  6. public class HttpsTrustManager implements X509TrustManager {  
  7.   
  8.     @Override  
  9.     public void checkClientTrusted(X509Certificate[] arg0, String arg1)  
  10.             throws CertificateException {  
  11.         // TODO Auto-generated method stub  
  12.   
  13.     }  
  14.   
  15.     @Override  
  16.     public void checkServerTrusted(X509Certificate[] arg0, String arg1)  
  17.             throws CertificateException {  
  18.         // TODO Auto-generated method stub  
  19.   
  20.     }  
  21.   
  22.     @Override  
  23.     public X509Certificate[] getAcceptedIssuers() {  
  24.         return new X509Certificate[]{};  
  25.     }  
  26.   
  27. }  
Importing a keystore (Recommended
If you are writing produciton quality code, then you should be looking at this approach. Have a all the keys in your application and create a SSLContext using those keystores. The created SSLContext can then be injected to SSLConnectionSocketFactory and remaining steps will be the same. 
  1. import javax.net.ssl.SSLContext;  
  2.   
  3. import org.apache.http.client.HttpClient;  
  4. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;  
  5. import org.apache.http.conn.ssl.SSLContexts;  
  6.   
  7. import org.apache.http.impl.client.CloseableHttpClient;  
  8. import org.apache.http.impl.client.HttpClients;  
  9. import java.io.File;  
  10. import java.io.FileInputStream;  
  11. import java.io.IOException;  
  12. import java.security.KeyStore;  
  13. import java.security.KeyStoreException;  
  14. import java.security.NoSuchAlgorithmException;  
  15. import java.security.cert.CertificateException;  
  16. import java.security.KeyManagementException;  
  17.   
  18. public class HttpClientFactory {  
  19.   
  20.     private static CloseableHttpClient client;  
  21.   
  22.     public static HttpClient getHttpsClient() throws Exception {  
  23.   
  24.         if (client != null) {  
  25.             return client;  
  26.         }  
  27.         SSLContext sslcontext = getSSLContext();  
  28.         SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,  
  29.                 SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);  
  30.         client = HttpClients.custom().setSSLSocketFactory(factory).build();  
  31.   
  32.         return client;  
  33.     }  
  34.   
  35.     public static void releaseInstance() {  
  36.         client = null;  
  37.     }  
  38.   
  39.     private SSLContext getSSLContext() throws KeyStoreException,   
  40.     NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException {  
  41.         KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());  
  42.         FileInputStream instream = new FileInputStream(new File("my.keystore"));  
  43.         try {  
  44.             trustStore.load(instream, "nopassword".toCharArray());  
  45.         } finally {  
  46.             instream.close();  
  47.         }  
  48.         return SSLContexts.custom()  
  49.                 .loadTrustMaterial(trustStore)  
  50.                 .build();  
  51.     }  
  52. }  
The only difference between the two approaches are the way the SSLContext been created.

2017年1月12日 星期四

[ Java 文章收集 ] Create Very Simple Jersey REST Service and Send JSON Data From Java Client

Source From Here 
Preface 
Recently I have to pass JSON data to REST Service and did not have any simple Client handy. But created very simple Java program which read JSON data from file and sends it to REST service. Representational State Transfer (REST) has gained widespread acceptance across the Web as a simpler alternative to SOAP– and Web Services Description Language (WSDL)-based Web services. Key evidence of this shift in interface design is the adoption of REST by mainstream Web 2.0 service providers—including Yahoo, Google, and Facebook—who have deprecated or passed on SOAP and WSDL-based interfaces in favor of an easier-to-use, resource-oriented model to expose their services. In this article, Alex Rodriguez introduces you to the basic principles of REST. 

Let’s start coding this: 
1. Create RESTFul Web Service 
* Java file: DemoRESTService.java
* web.xml file

2. Create RESTService Client 
* DemoRESTServiceClient.java file


Another must read: Spring MVC Example/Tutorial: Hello World – Spring MVC 3.2.1 

Step-1 
In Eclipse => File => New => Dynamic Web Project. Name it as “DemoWS”. Below tutorial also works with Tomcat 8. 


Step-2 Create Deployment Descriptor File 
If you don’t see web.xml (deployment descriptor) under WebContent\WEB-INF\ then follow these steps. Open web.xml and replace content with below contents: 

Step-3 Convert Project to Maven Project 

Follow this tutorial: http://crunchify.com/how-to-convert-existing-java-project-to-maven-in-eclipse/. Below is my pom.xml

Step-4 
Create RESTFul service: DemoRESTService.java. Here we will create two services: 
1. /api/demoService – POST call – we will use this with our test
2. /api/verify – GET call – just to make sure service started successfully

  1. package com.demo.tutorials;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.InputStream;  
  5. import java.io.InputStreamReader;  
  6.   
  7. import javax.ws.rs.Consumes;  
  8. import javax.ws.rs.GET;  
  9. import javax.ws.rs.POST;  
  10. import javax.ws.rs.Path;  
  11. import javax.ws.rs.Produces;  
  12. import javax.ws.rs.core.MediaType;  
  13. import javax.ws.rs.core.Response;  
  14.   
  15. @Path("/")  
  16. public class DemoRESTService {  
  17.     @POST  
  18.     @Path("/demoService")  
  19.     @Consumes(MediaType.APPLICATION_JSON)  
  20.     public Response crunchifyREST(InputStream incomingData) {  
  21.         StringBuilder strBuilder = new StringBuilder();  
  22.         try {  
  23.             BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));  
  24.             String line = null;  
  25.             while ((line = in.readLine()) != null) {  
  26.                 strBuilder.append(line);  
  27.             }  
  28.         } catch (Exception e) {  
  29.             System.out.println("Error Parsing: - ");  
  30.         }  
  31.         System.out.println("Data Received: " + strBuilder.toString());  
  32.   
  33.         // return HTTP response 200 in case of success  
  34.         return Response.status(200).entity(strBuilder.toString()).build();  
  35.     }  
  36.   
  37.     @GET  
  38.     @Path("/verify")  
  39.     @Produces(MediaType.TEXT_PLAIN)  
  40.     public Response verifyRESTService(InputStream incomingData) {  
  41.         String result = "DemoRESTService Successfully started..";  
  42.   
  43.         // return HTTP response 200 in case of success  
  44.         return Response.status(200).entity(result).build();  
  45.     }  
  46. }  
Step-5 
Deploy project DemoWS on Tomcat. Web project should be deployed without any exception. 


Step-6 Verify REST service 
Rest service should be accessible using this URL: http://127.0.0.1/DemoWS/api/verify 
If you try to access http://127.0.0.1/DemoWS/api/demoService then you will see error code 405 - Method not allowed – which is valid response. As you can see it’s POST call and should expect some data with the request. 
Step-7 
Next we will post below json into server: 
  1. {  
  2.     "tutorials": {  
  3.         "id""Crunchify",  
  4.         "topic""REST Service",  
  5.         "description""This is REST Service Example by Crunchify."  
  6.     }  
  7. }  
Create REST Call Client: 
- DemoRESTServiceClient.java 
  1. package com.demo.tutorials;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.InputStreamReader;  
  5. import java.io.OutputStreamWriter;  
  6. import java.net.URL;  
  7. import java.net.URLConnection;  
  8.   
  9. import org.json.JSONObject;  
  10.   
  11. public class DemoRESTServiceClient {  
  12.     public static void main(String args[]) throws Exception {  
  13.         // Step1:   
  14.         String jsonStr = "{\"tutorials\": {\"id\": \"Crunchify\",\"topic\": \"REST Service\",\"description\": \"This is REST Service Example by John.\"}}";  
  15.         JSONObject jsonObject = new JSONObject(jsonStr);  
  16.           
  17.         // Step2: Now pass JSON File Data to REST Service  
  18.         try {  
  19.             URL url = new URL(  
  20.                     "http://localhost/DemoWS/api/demoService");  
  21.             URLConnection connection = url.openConnection();  
  22.             connection.setDoOutput(true);  
  23.             connection.setRequestProperty("Content-Type""application/json");  
  24.             connection.setConnectTimeout(5000);  
  25.             connection.setReadTimeout(5000);  
  26.             OutputStreamWriter out = new OutputStreamWriter(  
  27.                     connection.getOutputStream());  
  28.             out.write(jsonObject.toString());  
  29.             out.close();  
  30.   
  31.             BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));  
  32.   
  33.             String line = null;  
  34.             while ((line=in.readLine()) != null) {System.out.printf("%s\n", line);}  
  35.             System.out.println("\nDemoWS REST Service Invoked Successfully..");  
  36.             in.close();  
  37.         } catch (Exception e) {  
  38.             System.out.println("\nError while calling DemoWS REST Service");  
  39.             System.out.println(e);  
  40.         }  
  41.     }  
  42. }  
Step-9 
Now let’s run Client Program by right click on DemoRESTServiceClient.java and you should see below two outputs: 
1) in Tomcat Console 

2) in Local Client Console 

Supplement 
The Java EE 5 Tutorial - Building Web Services with JAX-WS

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...