android将utf8内容发送给servlet

时间:2013-01-23 13:02:06

标签: java android hibernate servlets web

我使用Android将英语和阿拉伯语内容发送到Servlet,但数据会随服务器一起发送到服务器。怎么解决?这是Android中的代码:

StringEntity se = new StringEntity(gsonString);
se.setContentType("text/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json;charset=UTF-8"));
HttpPost httpRequest = new HttpPost(methodURL);
httpRequest.setEntity(se);
HttpResponse response = httpClient.execute(httpRequest,localContext);

Servlet代码

request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
    String line = in.readLine();
    String gsonString = line;
    while (line != null) {
        gsonString += line;
        line = in.readLine();
    }

有什么建议吗?

2 个答案:

答案 0 :(得分:5)

HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();

Gson gson = new Gson();
        String gsonString = gson.toJson(currentCustomer);
        Log.v("gson", gsonString);

        StringEntity se = new StringEntity(gson.toJson(currentCustomer),
                "UTF-8");
HttpPost httpRequest = new HttpPost(methodURL);
        httpRequest.setHeader("customerRegisrationData", gsonString);
        httpRequest.setEntity(se);

        HttpResponse response = httpClient.execute(httpRequest,
                localContext);

答案 1 :(得分:1)

使用这些方法

HttpPost httpPost = new HttpPost(method_url);

StringEntity postEntity = new StringEntity(HTTP.UTF_8);
httpPost.setEntity(postEntity)

OR

httpPost.setEntity(new UrlEncodedFormEntity(postData));