UTF-8 格式的 JAVA Http POST 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18823357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:23:40  来源:igfitidea点击:

JAVA Http POST request in UTF-8

javahttputf-8

提问by tom

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

我的 J2EE 应用程序能够从 JSP 页面接收 POST 请求,这没有问题。

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

但是如果我使用另一个 java 应用程序发送 POST 请求,则接收到的参数不是 UTF-8 字符串。

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

感谢您的回复

回答by Christoffer Hammarstr?m

The docs for DataOutputStream.writeBytes(String)says

的文档DataOutputStream.writeBytes(String)

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.

将字符串作为字节序列写入底层输出流。通过丢弃其高八位顺序写出字符串中的每个字符。如果没有抛出异常,则写入的计数器增加 s 的长度。

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

而是使用 cox.getOutputStream().write(query.getBytes("UTF-8"));

DataOutputStreamis redundant here.

DataOutputStream这里是多余的。

回答by Emanuele

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-3seem to support your spechial character ?

https://en.wikipedia.org/wiki/ISO/IEC_8859-3似乎支持你的特殊性格?

回答by erenerdogan

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;
}
}

回答by Julian Reschke

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

a) “application/x-www-form-urlencoded”没有字符集参数;它本质上仅限于 ASCII

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

b) 要发送非 ASCII 字符,您需要将它们编码为 UTF-8(不是客户端的默认编码)并对其进行百分比转义;有关详细信息,请参阅http://www.w3.org/TR/2014/REC-html5-20141028/forms.html#application/x-www-form-urlencoded-encoding-algorithm

回答by Arkadiusz

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();

回答by Dkngit

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

基于 HttpClient 的示例“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);