只发送一个带有http Post的字符串但是错误

时间:2014-03-15 09:47:13

标签: java android

3 个答案:

答案 0 :(得分:1)

在发送到Web服务器之前,您需要使用适当的charset 对字符串进行编码。否则,String将在所用平台的默认字符集中进行编码。检查服务器和程序是否都使用正确的字符集来编写和读取字符串

比如说,它是UTF-8,从String创建ByteArray,编码UTF-8字符集,代码如下

new String(YOUR_BYTE_ARRAY, Charset.forName("UTF-8"));

在服务器端使用相同的字符集String将编码的ByteArray读入UTF-8可以按如下方式完成

YOUR_UTF8_STRING.getBytes("UTF-8");

希望这澄清!

答案 1 :(得分:1)

尝试此更改:

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));

服务器还必须能够处理UTF-8才能正常工作。

或者,如果文本将呈现为HTML,则可以对整个文本进行编码,以便服务器不需要支持UTF-8。

String str ="Nhập nội dung bình luận để gửi đi!";

这是html编码,而不是URL编码。不幸的是,据我所知,Java不包含html编码器。你必须使用第三方库。

这个帖子列出了几个库: Is there a JDK class to do HTML encoding (but not URL encoding)?

使用其他线程中的示例完全破解。尝试这样的事情......

public void post() {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(link);
    String str ="Nhập nội dung bình luận để gửi đi!";
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("file", encodeHTML(str)));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
}
public static String encodeHTML(String s)
{
    StringBuffer out = new StringBuffer();
    for(int i=0; i<s.length(); i++)
    {
        char c = s.charAt(i);
        if(c > 127 || c=='"' || c=='<' || c=='>')
        {
           out.append("&#"+(int)c+";");
        }
        else
        {
            out.append(c);
        }
    }
    return out.toString();
}

答案 2 :(得分:0)

从应用程序发送时对您的网址进行编码:

// import java.net.URLEncoder;
str = URLEncoder.encode(str, "UTF-8");

从接收器解码字符串:

// import java.net.URLDecoder;
str = URLDecoder.decode(str, "UTF-8");