Posts

Showing posts with the label Java IO

Java HTPPS SSL Client

HTTPS secure HTTP connection , HTTP over secure socket layer (SSL). To establish an HTTPS connection to a remote server , you should use the certificate obtained by the server. This certificate is validated using a local trust store. Default trust store is /lib/security/cacerts. You can define another trust store using keytool application in /bin. Certificates can be added to trust store with keytool application also. You should give trust store parameter to JVM like this : -Djavax.net.ssl.trustStore=/mypath/my.keystore -Djavax.net.ssl.trustStorePassword=mypassword Here is the sample code to create an HTTPS connection: package javacream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URLEncoder; import java.security.Security; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; public class HTTPSClient { public static void main(String[] args...

Read and Write Files in Java

Here is a sample code I just wrote. This class copies one file to another. By understanding this code below , you will comphrend both reading from and writing to file concepts in java. I used FileInputStream and FileOutputStream in this code. package javacream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class FileUtil { public static void copyFile(String strInputFileName , String strOutputFileName) throws IOException { //Prepare file objects File fInputFile = new File(strInputFileName); File fOutputFile = new File(strOutputFileName); //Prepare read write streams from file objects FileInputStream fis = new FileInputStream(fInputFile); FileOutputStream fos = new FileOutputStream(fOutputFile); int c; // read from the input file and write to the output file while ((c = fis.read()) != -1) { ...

Java HTTP GET POST

As you know HTTP (Hypertext Transfer Protocol) is the transport protocol of www. Java has a strong support for HTTP. HTTP addresses uses addressing syntax called URL (for example http://www.java.com). HTTP is based on TCP. HTTP GET This is the most widespred type of HTTP request. If you write http://www.java.com/ on your browser you have already made an HTTP GET Request. Here is a sample : public static String doGET(String strURL) throws IOException { String response = null ; InputStream in = null ; try { // setup url connection URL url = new URL(strURL); HttpURLConnection urlConn = (HttpURLConnection) url .openConnection(); in = urlConn.getInputStream(); StringBuilder sb = new StringBuilder(); int i; while ((i = in.read()) > -1) sb....