import java.io.*;
import java.net.URLEncoder;
import java.net.URLDecoder;
import java.nio.charset.Charset;
public class URLencode_object {
public static void main(String[] args){
try {
student jones=new student("jones","senior",90);
System.out.println(" ///An instance .toString()");
System.out.println(jones.toString());
System.out.println("The length: "+jones.toString().length());
byte [] theobjectbytes = makeByteArray(jones);
System.out.println("The length of the object byte array: "+theobjectbytes.length);
System.out.println("\n ///The object 'Hexified'");
String thehexversion=Byte2String(theobjectbytes);
System.out.println(thehexversion);
System.out.println("The length: "+thehexversion.length());
System.out.println("\n ///The 'Hexified' URLencoded");
String hexencoded=URLEncoder.encode(thehexversion,"UTF-8");
System.out.println(hexencoded);
System.out.println(" The length of the encoded string: "+hexencoded.length());
System.out.println("\n ///Finally URLencode the object bytes");
String encoded=URLEncoder.encode(new String(theobjectbytes),"UTF-8");
System.out.println(encoded);
System.out.println(" The length of the encoded string: "+encoded.length());
System.out.println("\n ///the name");
String decoded=URLDecoder.decode(encoded,"UTF-8");
theobjectbytes=decoded.getBytes();
student ob=get_student(theobjectbytes);
System.out.println(ob.name);
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
public static byte[] makeByteArray(student mystudent){
ByteArrayOutputStream baos =null;
try {
baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(mystudent);
} catch (Exception e) {
System.out.println(e);
}
return baos.toByteArray();
}
public static student get_student(byte [] theobjectbytes){
try {
ByteArrayInputStream bais = new ByteArrayInputStream(theobjectbytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return(student)ois.readObject();
} catch (Exception e) {
System.out.println(e);
}
return new student("noname","noclass",0);
}
public static String Byte2String(byte[] barray){
StringBuilder result = new StringBuilder();
for (byte b : barray)
result.append(String.format("%02X", b));
return result.toString();
}
}
ASCII->URL encoding