Java character set and encoding/decoding

1 minute read

Convert character set

public class StringFormatter {

    // convert UTF-8 to internal Java String format
    public static String convertUTF8ToString(String s) {
        String out = null;
        try {
            out = new String(s.getBytes("ISO-8859-1"), "UTF-8");
        } catch (java.io.UnsupportedEncodingException e) {
            return null;
        }
        return out;
    }

    // convert internal Java String format to UTF-8
    public static String convertStringToUTF8(String s) {
        String out = null;
        try {
            out = new String(s.getBytes("UTF-8"), "ISO-8859-1");
        } catch (java.io.UnsupportedEncodingException e) {
            return null;
        }
        return out;
    }

}

String javastr = "This normal internal java string".
String utfstr = StringFormatter.convertStringToUTF8(javastr);

Apache HttpClient

addHeader(String name, String value

Adds a header to this message. The header will be appended to the end of the list. setHeader method override headers if header’s names are same. But addHeader method doesn’t. It adds headers even header’s name are same

setHeader(String name, String value

Overwrites the first header with the same name. The new header will be appended to the end of the list, if no header with the given name can be found.

    httpPost.setEntity(new StringEntity(json, "UTF-8"));
    httpPost.addRequestHeader("Content-Type", "text/plain;charset=UTF-8");

    httpPost.addHeader("AuthenticationKey",authenticationKey);
    httpPost.addHeader("Content-Type","application/json");

    httpPost.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
    httpPost.setHeader("Pragma", "no-cache"); // HTTP 1.0
    httpPost.setHeader("X-Requested-With", "XMLHttpRequest");

Usage

URI urlObject = new URI(url,"UTF-8");
HttpClient httpclient = new DefaultHttpClient();

List<NameValuePair> formparams = URLEncodedUtils.parse(urlObject,"UTF-8");
UrlEncodedFormEntity entity;
entity = new UrlEncodedFormEntity(formparams);

HttpPost httppost = new HttpPost(urlObject.getPath());
httppost.setEntity(entity);
httppost.addHeader("Content-Type","application/x-www-form-urlencoded");

HttpResponse response = httpclient.execute(httppost);

HttpEntity entity2 = response.getEntity();

Java URLConnection

// Iterate over query params from urlObject.getQuery() like
while(en.hasMoreElements()){
    String paramName  = (String)en.nextElement(); // Iterator over yourListOfKeys
    String paramValue = yourMapOfValues.get(paramName); // replace yourMapOfNameValues
    str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
}
try{
    URL u = new URL(urlObject.getPath()); //here's the url path from your urlObject
    URLConnection uc = u.openConnection();
    uc.setDoOutput(true);
    uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    PrintWriter pw = new PrintWriter(uc.getOutputStream());
    pw.println(str);
    pw.close();

    BufferedReader in = new BufferedReader(new 
            InputStreamReader(uc.getInputStream()));
    String res = in.readLine();
    in.close();
    // ...
}

Tags:

Categories:

Updated:

Leave a comment