Thursday, January 19, 2012

HTTP GET/POST request from java

HTTP GET Requests

An HTTP GET request is all you need to retrieve basic search results from the Yahoo! Search Web Service. GET requests are easy to debug because you can paste it in your web browser and quickly see if the query has been constructed properly. Some web services require requests via POST for tasks such as image uploading or the modification of HTTP headers to set cookies. We will cover both GET and POST requests in the following examples.
The first example is a request for the keyword "umbrella" that returns 10 results:
String request = "http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=umbrella&results=10";
We make a simple HTTP GET request to retrieve the results:
HttpClient client = new HttpClient();

        GetMethod method = new GetMethod(request);


  // Send GET request

        int statusCode = client.executeMethod(method);
Next, we process the response from Yahoo! Web Services and print the XML response to the console:
InputStream rstream = null;

        rstream = method.getResponseBodyAsStream();

 BufferedReader br = new BufferedReader(new InputStreamReader(rstream));

    String line;

    while ((line = br.readLine()) != null) {

    System.out.println(line);

    }

    br.close();
A complete code example is available in the file YahooWebServiceGet.java

HTTP POST Requests

POST requests are used by web browsers when submitting data from HTML forms. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.
For POST requests, we construct the POST data separately from the request URL and parameters.
String request = "http://api.search.yahoo.com/WebSearchService/V1/webSearch";
    HttpClient client = new HttpClient();

    PostMethod method = new PostMethod(request);

    // Add POST parameters

    method.addParameter("appid","YahooDemo");

    method.addParameter("query","umbrella");

    method.addParameter("results","10");


    // Send POST request

    int statusCode = client.executeMethod(method);

    InputStream rstream = null;

    
    // Get the response body

    rstream = method.getResponseBodyAsStream();

 
The response is the same as the first example and can be processed in the same way.
A complete code example is available in the file YahooWebServicePost.java

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

  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.io.OutputStreamWriter;
  4. import java.net.URL;
  5. import java.net.URLConnection;
  6. import java.net.URLEncoder;
  7.  
  8. public class POSTDATA {
  9.  
  10.  
  11.     public POSTDATA() {
  12.     }
  13.     public static void main(String[] args) {
  14.         try {
  15.         // Construct data
  16.         String data = URLEncoder.encode("fName", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
  17.         data += "&" + URLEncoder.encode("lName", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
  18.  
  19.         // Send data
  20.         URL url = new URL("http://localhost/TUT/POSTDATA/post.php");
  21.         URLConnection conn = url.openConnection();
  22.         conn.setDoOutput(true);
  23.         OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
  24.         wr.write(data);
  25.         wr.flush();
  26.  
  27.         // Get the response
  28.         BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  29.         String line;
  30.         while ((line = rd.readLine()) != null) {
  31.             System.out.println(line);
  32.         }
  33.         wr.close();
  34.         rd.close();
  35.     } catch (Exception e) {
  36.     }
  37.     }
  38.  
  39. }

....................................................
http://www.aviransplace.com/2008/01/08/make-http-post-or-get-request-from-java/
http://developer.yahoo.com/java/howto-reqRestJava.html#get 
http://hc.apache.org/httpclient-3.x/tutorial.html
http://www.vogella.de/articles/ApacheHttpClient/article.html

Tuesday, January 17, 2012

How to generate HTTP post request to server/service using java

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;


  serviceEndpoint = "end point of the service";

        webServicePayload = "xml file in the form of string";

        HttpClient client = new HttpClient();
        // TODO make a service end point change?
        PostMethod post = new PostMethod(serviceEndpoint);

        StringRequestEntity body = new StringRequestEntity(webServicePayload,
                "text/xml", "UTF-8");
        post.addRequestHeader("SOAPAction", "\"\"");
        post.setRequestEntity(body);

      
        int status = client.executeMethod(post);

        String responseBody = post.getResponseBodyAsString();

How to compile jdk 1.5 generated .class/java file with lower jdk versions


 Cross-Compilation Options


By default, classes are compiled against the bootstrap and extension classes of the platform that javac shipped with. But javac also supports cross-compiling, where classes are compiled against a bootstrap and extension classes of a different Java platform implementation. It is important to use -bootclasspath and -extdirs when cross-compiling; see Cross-Compilation Example below.
-target version
Generate class files that will work on VMs with the specified version. The default is to generate class files to be compatible with the JDK 5 VM. When the -source 1.4 or lower option is used, the default target is 1.4. The versions supported by javac are:
1.1Generate class files that will run on VMs in JDK 1.1 and later.
1.2Generate class files that will run on VMs in JDK 1.2 and later, but will not run on 1.1 VMs.
1.3Generate class files that will run on VMs in JDK 1.3 and later, but will not run on 1.1 or 1.2 VMs.
1.4Generate class files that will run on VMs in JDK 1.4 and later, but will not run on 1.1, 1.2 or 1.3 VMs.
1.5Generate class files that are compatible only with JDK 5 VMs.
5Synonym for 1.5
-bootclasspath bootclasspath
Cross-compile against the specified set of boot classes. As with the user class path, boot class path entries are separated by semicolons (;) and can be directories, JAR archives, or ZIP archives.
-extdirs directories
Cross-compile against the specified extension directories. Directories is a semicolon-separated list of directories. Each JAR archive in the specified directories is searched for class files.

Cross-Compilation Example


Here we use javac to compile code that will run on a 1.4 VM.
% javac -target 1.4 -bootclasspath jdk1.4.2/lib/classes.zip \
             -extdirs "" OldCode.java
The -target 1.4 option ensures that the generated class files will be compatible with 1.4 VMs. By default, javac compiles for JDK 5.The Java 2 SDK's javac would also by default compile against its own bootstrap classes, so we need to tell javac to compile against JDK 1.4 bootstrap classes instead. We do this with -bootclasspath and -extdirs. Failing to do this might allow compilation against a Java 2 Platform API that would not be present on a 1.4 VM and would fail at runtime.
 .................................................
 it generally occurs if a higher JDK version  is used to compile the source file and  a lower JDK version is used to run the program. for example if you compile your java source file in JDK 1.5 and you will try to run it on JDK 1.4 you will get error


UnSupportedClassVersionError will not tell you for which class it’s coming. So if you are using multiple third party jars in your application you find that it comes at a particular part when JVM tries to load a class from a particular jar. anyway we all know that latest version of JDK is 1.6 so maximum version of class filecould be generated by JDK 6, so by using JDK 6 we can solve UnSupportedClassVersionError, but many times its not easy to just move to higher JDK version. So I would suggest:

1) Find out due to which jar or class file this UnSupportedClassVersionError is coming?
2) Try to compile source code of that jar with the JDK version you are using to run your program, if source is available.
3) If you don't have source try to find the compatible version of that library.
4) Increase the JRE version you are using to run your program.
 
Following are the major version of class file format in standard JDK environment.

JDK 1.1 = 45
JDK 1.2 = 46
JDK 1.3 = 47
JDK 1.4 = 48
JDK 1.5 = 49
JDK 1.6 = 50
 
 
1) If you encounter UnSupportedClassVersionError, check the JRE version you are using to run program and switch to higher version for quick solution.
2) java.lang.UnsupportedClassVersionError is derived from java.lang.LinkageError, so it will not be detected in compile time and it will only come on runtime, precisely when JVM tries to load a class.
3) Class file format which is identified using major version and minor version. Class file format is assigned when you compile source file and its depends on JDK version used to compile.
4) Its always best practice to use same version of java for compilation and execution to avoid any chance of UnSupportedClassVersionError.
5) UnSupportedClassVersionError is not related to java classpath , so don't confuse this with NoClassDefFoundError or ClassNotFoundException. 

Wednesday, January 11, 2012

How to create customized Date format in java

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        String timestamp = dateFormat.format(date);


Wednesday, January 4, 2012

how to catch java script values to java/jsp


<script>
var connectionValue=0;

//var input=<input type='hidden' name='connection'+connectionValue id='connection'+connectionValue />;

function mappingConnections(from,to){
//alert('from'+from);
alert('to'+to);
document.getElementById('mappingConnections').innerHTML+="<input type='hidden' id='mconnection"+connectionValue+"' />";
alert('from1 :'+from);
alert('connection1 :'+from);
alert('from0 :'+document.getElementById('mappingConnections').innerHTML);
var abc = from+"::"+to;
MappingConnection[connectionValue] = abc;

//document.getElementById('mconnection'+connectionValue).value=
alert('from01 :');
alert('from0 :'+document.getElementById('mappingConnections').innerHTML);
/*var field = document.connection.createElement("input");
alert('from1 :'+from);
field.setAttribute("type","hidden");
alert('from2 :'+from);
field.setAttribute("value",from+"::"+to);
alert('from3 :'+from);
field.setAttribute("name","connection"+connectionValue++);
alert('from4 :'+from);
document.getElementById("connection").appendChild(field);*/
alert('from5 :'+from);
connectionValue++;
}

function allConnections(){
var totalvalue;
alert(connections.length);
for(i =0 ; i< connectionValue ; i++)
    {
    document.getElementById('mconnection'+i).value=MappingConnection[i];
        totalvalue=totalvalue+"$$"+MappingConnection[i];
    alert(" i value :"+document.getElementById('mconnection'+i).value);
    }
    document.getElementById('connectionValue').value=connectionValue;
        alert("total value"+totalvalue);
        document.getElementById('mconnection1').value=totalvalue;
 alert(connections);
   
}
mappingConnection(value1,value2);
</script>
<form method="post"  name="connection" action="new.htm">
               
             <div  id="mappingConnections">
             <input type="hidden" name="connectionValue" id="connectionValue"/>
                          <input type="hidden" name="mconnection1" id="mconnection1"/>
              </div>
                                 
              <div class="buttonsDiv">
                     <input name="" type="button" value="Back" class="standerd_btn" onClick="parent.location='mapFields.htm'" />
                     <input name="Input" type="submit" value="Next" class="standerd_btn" onClick="allConnections();"/>
              </div>
                        </form>

useful link for java practice

Tuesday, January 3, 2012

how to add dynamic html fields using javascript

var counterText = 0;
var counterRadioButton = 0;
var counterCheckBox = 0;
var counterTextArea = 0;
function addAllInputs(divName, inputType){
     var newdiv = document.createElement('div');
     switch(inputType) {
          case 'text':
               newdiv.innerHTML = "Entry " + (counterText + 1) + " <br><input type='text' name='myInputs[]'>";
               counterText++;
               break;
          case 'radio':
               newdiv.innerHTML = "Entry " + (counterRadioButton + 1) + " <br><input type='radio' name='myRadioButtons[]'>";
               counterRadioButton++;
               break;
          case 'checkbox':
               newdiv.innerHTML = "Entry " + (counterCheckBox + 1) + " <br><input type='checkbox' name='myCheckBoxes[]'>";
               counterCheckBox++;
               break;
          case 'textarea':
        newdiv.innerHTML = "Entry " + (counterTextArea + 1) + " <br><textarea name='myTextAreas[]'>type here...</textarea>";
               counterTextArea++;
               break;
          }
     document.getElementById(divName).appendChild(newdiv); 
}
.........................................................................................................................................................................
<script src="/wp-includes/js/addInput.js" language="Javascript" type="text/javascript"></script>
<form method="POST">
     <div id="dynamicInput">
          Entry 1<br><input type="text" name="myInputs[]">
     </div>
     <input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
</form> 
 
var counter = 1;
var limit = 3;
function addInput(divName){
     if (counter == limit)  {
          alert("You have reached the limit of adding " + counter + " inputs");
     }
     else {
          var newdiv = document.createElement('div');
          newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
          document.getElementById(divName).appendChild(newdiv);
          counter++;
     }
}