0

I have a question regarding UTF-8 encoding when sending strings containing special characters using HttpServiceClient (Apache)

I have this small piece of code below where the method takes string and sends it via Http(which is not fully complete in the code).

Although the decoded string seems to work without problems, I would like to know if the method.addparameter or httpClient.execute(method) encodes the string again. We have the problem that at the client side the strings seem doubly encoded!

eg. strReq = äöü

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.net.URLCodec;
import org.apache.commons.httpclient.methods.PostMethod;



public class Demo {
    public static void Test(String strReq) throws CancellationException, IOException, DecoderException {

        PostMethod method = null;

            method = new PostMethod("www.example.com");

            // Encode the XML document.
            URLCodec codec = new URLCodec();
            String requestEncoded = new String(strReq);
            try {
                requestEncoded = codec.encode(strReq);

            } catch (EncoderException e) {

            }

            System.out.println("encoded req = "+requestEncoded);

            method.addParameter(Constants.Hdr, requestEncoded);


            String  str2 = codec.decode(requestEncoded);

            System.out.println("str2 ="+str2);
        }
user907810
  • 3,208
  • 10
  • 39
  • 47
  • the default post method is application/x-www-form-urlencoded so you don't need to do it yourself. – gigadot Sep 11 '12 at 09:36
  • you mean URLCodec here is not needed?? – user907810 Sep 11 '12 at 10:35
  • But I am not encoding the URL... – user907810 Sep 11 '12 at 10:35
  • if you want to send a file, you should set your post method to multipart/form-data and don't worry about encoding the file. it will be dealt with my the library – gigadot Sep 11 '12 at 10:39
  • sorry what library. I am lost. Could you please elaborate? Are you saying that URLCodec for the string is not needed? – user907810 Sep 11 '12 at 11:01
  • To be honest I have encoded it also because I could not send a string which is greater than 4096 bytes :( – user907810 Sep 11 '12 at 11:20
  • the httpclient library will deal with all the underlying encoding if needed. you don't want to send a file using default method, which is application/x-www-form-urlencoded because you cannot send a big file. – gigadot Sep 11 '12 at 11:25
  • http://stackoverflow.com/questions/2646194/multipart-file-upload-post-request-from-java – gigadot Sep 11 '12 at 11:27

0 Answers0