When to Use?

This is used when we want to access the any http or https url and then receive the data it sends back in java. Following is a sample code on how it can be used.

How to Use?
Replace the url you want to use and also parameters like param1, param2 which i used in the code to send parameters in encoded format. and then run...


I used it when I got into a situation where I need to send request to third party sever for fetching GPS related details. And the server responds back with a XML file. So, I should be capable enough to receive it and then parse it to get what exactly I wanted. I found this method very useful...

.......................................................................................................................................

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import javax.net.ssl.HttpsURLConnection;


public class http_https_connection extends HttpServlet {
private static final String CONTENT_TYPE = "text/html";

public AtomDemo() {
super();
}

public void destroy() {
super.destroy();
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out=response.getWriter();
getPostData(request,response);
out.flush();
out.close();
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.flush();
out.close();

}


private void getPostData(HttpServletRequest request,HttpServletResponse response){
String RevcodeData=null;
String content=null;
String address = null;
try{

response.setContentType("text/html");

URL url;
URLConnection urlConn;

url = new URL("http://any host name.com");

urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");

// Send POST output.
cgiInput = new DataOutputStream(urlConn.getOutputStream());

content = "keyword=" + URLEncoder.encode("param1","UTF-8")
+ "&productName="+ URLEncoder.encode("param2","UTF-8");

cgiInput.writeBytes(content);
cgiInput.flush();
cgiInput.close();

BufferedReader cgiOutput =
new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
PrintWriter servletOutput = response.getWriter();
String line = null;
while (null != (line = cgiOutput.readLine())){
servletOutput.println(line);
System.out.println(line);
}
cgiOutput.close();

}catch (Exception e) {
// TODO: handle exception
}

}


public void init() throws ServletException {
// Put your code here
}

}
  • Use this to create indexes for you tables in database which helps to retreive data faster.
  • Indexes act like book marks which we keep in a book to access any page instantly.
Command Syntax:

CREATE INDEX
Name of index ON table name (column1,column2,....)

Sample that I used:

CREATE INDEX GPSLOCATION_INDX1 ON GPSLOCATIONS
(LASTUPDATE, PHONENUMBER)

you are getting below exception?

" unable to find valid certification path to requested target
" or
" Trying to open an SSL connection to a host using JSSE / JAVA"

Then, Go through this post...

............................................................................................................................................

When this comes into picture?


when trying to open an SSL connection to a host using JSSE. What this usually means is that the server is using a test certificate (possibly generated using keytool) rather than a certificate from a well known commercial Certification Authority such as Verisign or GoDaddy. Web browsers display warning dialogs in this case, but since JSSE cannot assume an interactive user is present it just throws an exception by default.

............................................................................................................................................

Manual Process:


1) Open the https website in any browser (say, Internet Explorer 8), whose certificate is needed.
2) You will find a LOCK symbol beside address bar. Click it.
3) Select View Certificate options.
4) This pops out a certificate window with 3 tabs (General, Details, Certification path).
5) Goto Details tab and click Copy to file and then next, next, next.... select path and finish
6) Certificate .cer of that site you are accessing is exported to ur PC.
7) Goto command prompt and set its path to your . cer that we exported in above step.
8) Import your .cer file into keystore using following command.
keytool -import -alias somename -file our_cer_file_name.cer -keystore keystore_name

you have successfully imported certificate of https site that you are accessing.

9) Now you can check its presence in key store using following command:
keytool -list -keystore keystore_name

Note: listing command works when you are in the path where you keystor is present. Generally default keystore of java is available in you jdk/lib/security folder with name cacerts.
in my PC it is in C:\Program Files\Java\jdk1.6.0_16\jre\lib\security

............................................................................................................................................

Automatic Process:
( It can be done in two ways. Through GUI or Command Prompt.)

Steps for GUI way of importing certificate:

1) Open the https website in any browser (say, Internet Explorer 8), whose certificate is needed.
2) You will find a LOCK symbol beside address bar. Click it.
3) Select View Certificate options.
4) This pops out a certificate window with 3 tabs (General, Details, Certification path).
5) Goto General tab and click Install Certificate and then next then select Keystore and finish.
you have successfully imported certificate of https site that you are accessing.
............................................................................................................................................

Steps for Command Prompt way of importing certificate:

1) copy java code of InstallCert which I found it in Andreas Sterbenz`s Former
http://blogs.sun.com/andreas/entry/no_more_unable_to_find
2) Compile it java InstallCert ecc.fedora.redhat.com from command prompt and follow steps given in above link.

you have successfully imported certificate of https site that you are accessing.
Below is java class that does Base 64 encoding.

public class Base64 {

private static final String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz" + "0123456789" + "+/";

private static final int splitLinesAt = 76;

public static byte[] zeroPad(int length, byte[] bytes) {
byte[] padded = new byte[length]; // initialized to zero by JVM
System.arraycopy(bytes, 0, padded, 0, bytes.length);
return padded;
}

public static String encode(String string) {

String encoded = "";
byte[] stringArray;
try {
stringArray = string.getBytes("UTF-8"); // use appropriate encoding string!
} catch (Exception ignored) {
stringArray = string.getBytes(); // use locale default rather than croak
}
// determine how many padding bytes to add to the output
int paddingCount = (3 - (stringArray.length % 3)) % 3;
// add any necessary padding to the input
stringArray = zeroPad(stringArray.length + paddingCount, stringArray);
// process 3 bytes at a time, churning out 4 output bytes
// worry about CRLF insertions later
for (int i = 0; i < stringArray.length; i += 3) {
int j = ((stringArray[i] & 0xff) << 16) +
((stringArray[i + 1] & 0xff) << 8) +
(stringArray[i + 2] & 0xff);
encoded = encoded + base64code.charAt((j >> 18) & 0x3f) +
base64code.charAt((j >> 12) & 0x3f) +
base64code.charAt((j >> 6) & 0x3f) +
base64code.charAt(j & 0x3f);
}
// replace encoded padding nulls with "="
return splitLines(encoded.substring(0, encoded.length() -
paddingCount) + "==".substring(0, paddingCount));

}
public static String splitLines(String string) {

String lines = "";
for (int i = 0; i < string.length(); i += splitLinesAt) {

lines += string.substring(i, Math.min(string.length(), i + splitLinesAt));
lines += "\r\n";

}
return lines;

}
/* public static void main(String[] args) {

for (int i = 0; i < args.length; i++) {

System.err.println("encoding \"" + args[i] + "\"");
System.out.println("007 is now "+encode("007"));

}

} */

}

................................
How to use it?
................................
  1. 1) Copy above code.
  2. 2) Paste it in a .java file with name "Base64" .
  3. 3) Import above class in java file where you you would like to use Base64 encoding.
  4. 4) use, String encoded_string = Base64.encode("any string");
  5. 5) encoded_string contains your encoded string.