9

My J2EE application is able to receive POST request from a JSP page, no problem about that.

But if I use another java application to send a POST request, the parameter received is not an UTF-8 string.

Here there is my code:

URL url = new URL("http://localhost:8080/ITUNLPWebInterface/SimpleApi");
HttpURLConnection cox = (HttpURLConnection) url.openConnection();

cox.setDoInput(true);
cox.setDoOutput(true);
cox.setRequestMethod("POST");
cox.setRequestProperty("Accept-Charset", "UTF-8");
cox.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
cox.setRequestProperty("charset", "UTF-8");

DataOutputStream dos = new DataOutputStream(cox.getOutputStream());
String query = "tool=ner&input=şaşaşa";
dos.writeBytes(query);
dos.close();

Am I doing something wrong?

Thanks for your reply

2
  • You try application/x-www-form-urlencoded; charset=utf-8 alter for application/x-www-form-urlencoded Commented Sep 16, 2013 at 8:23
  • Same, the server cannot see the parameters... Commented Sep 16, 2013 at 8:49

6 Answers 6

14

this work!!!.

package com.erenerdogan.utils;

import com.erenerdogan.webservice.ServiceInterface;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

/**
 *
 * @author erenerdogan
 */
public class WebService 
{
private String server;

    public WebService(String server) {
        this.server = server;
    }

private HttpPost createPostRequest(String method, Map<String, String> paramPairs){
    // Creating HTTP Post
    HttpPost httpPost = new HttpPost(server + "/" + method);
    // Building post parameters
    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(paramPairs.size());
    for (String key : paramPairs.keySet()){
        nameValuePair.add(new BasicNameValuePair(key, paramPairs.get(key)));
            System.out.println("Key : "+ key + " - Value : "+ paramPairs.get(key) );
    }

    // Url Encoding the POST parameters
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair,"UTF-8"));
    } catch (UnsupportedEncodingException e) {
        // writing error to Log
        e.printStackTrace();
    }
    return httpPost;
}

public String callServer(String method, Map<String, String> paramPairs) throws ClientProtocolException, IOException{

    // Creating HTTP client
    HttpClient httpClient = new DefaultHttpClient();

    HttpParams httpParameters = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 10 * 1000);
    HttpConnectionParams.setSoTimeout(httpParameters, 3 * 1000);
    HttpResponse httpResponse = httpClient.execute(createPostRequest(method, paramPairs));
    HttpEntity httpEntity = httpResponse.getEntity();
    String xml = EntityUtils.toString(httpEntity);

    return xml;
}
}
Sign up to request clarification or add additional context in comments.

1 Comment

Tanks the most important line is` httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair,"UTF-8"));` It worked for me
6

The docs for DataOutputStream.writeBytes(String) says

Writes out the string to the underlying output stream as a sequence of bytes. Each character in the string is written out, in sequence, by discarding its high eight bits. If no exception is thrown, the counter written is incremented by the length of s.

Instead use cox.getOutputStream().write(query.getBytes("UTF-8"));

DataOutputStream is redundant here.

4 Comments

The method writeBytes(String) in the type DataOutputStream is not applicable for the arguments (byte[]) So I don't think we can use that way, no ?
Thank you for your reply, I just did it, but still '?' instead of special character.
What encoding are you saving your source file in, and do you specify it to javac?
Ok, I found the bug, to make my request work with firefox (direct request), I had to receive in ISO-8859-1 and after convert into UTF-8. So now it's working but not anymore the firefox GET request form the URI address bar. At least...
2

try this

HttpClient client = new DefaultHttpClient();
HttpPost port = new HttpPost("http://localhost:8080/ITUNLPWebInterface/SimpleApi");

List<NameValuePair> parameters = new ArrayList<NameValuePair>(3);
parameters.add(new BasicNameValuePair("tool", "ner"));
parameters.add(new BasicNameValuePair("input", "şaşaşa"));
//post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
post.setEntity(new UrlEncodedFormEntity(params, "ISO-8859-3")); //try this one

HttpResponse resp = client.execute(post);

https://en.wikipedia.org/wiki/ISO/IEC_8859-3 seem to support your spechial character ş

5 Comments

Ok, I did, it's same, on the server I obtain, '?' instead of special character.
In my test case it works, can you post your result and your class that reads those params? so that iI can help you better
try other 2 things... try to add ISO-8859-3 as charset and try to edit post.setEntity(new UrlEncodedFormEntity(params, "ISO-8859-3"));
I just tried it, and still '?', I will become crazy. By the way, it's ISO-8859-9 because it's turkish, in my case.
pls put you server code, or some test case just to reproduce your behaviour
2

It works form me:

connection = (HttpURLConnection) url.openConnection();
...
byte[] data = message.getBytes("UTF-8");
...
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.write(data);
wr.close();

Comments

0

a) "application/x-www-form-urlencoded" doesn't have a charset parameter; it's essentially limited to ASCII

b) to send non-ASCII characters, you need to encode them in UTF-8 (not the client's default encoding) and percent-escape them; see http://www.w3.org/TR/2014/REC-html5-20141028/forms.html#application/x-www-form-urlencoded-encoding-algorithm for the details.

Comments

0

base on HttpClient's Example "FluentRequests.java":

Content content = Request.Post("http://localhost:8080/ITUNLPWebInterface/SimpleApi")
        .body(new UrlEncodedFormEntity(
                Form.form()
                .add("tool", "ner")
                .add("input", "şaşaşa")
                .build(), "UTF-8"))
        .execute().returnContent();
System.out.println(content);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.