有以下Java代码:
public static void register(UserInfo info) throws ClientProtocolException, IOException, JSONException, RegistrationException {
List<NameValuePair> params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", info.getName()));
params.add(new BasicNameValuePair("email", info.getEmail()));
params.add(new BasicNameValuePair("pass", info.getPassword()));
params.add(new BasicNameValuePair("genus", String.valueOf(info.getGenus())));
String response=doPostRequest(params, REGISTRATION_URL);
}
private static String doPostRequest(List<NameValuePair> params, String url) throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
return getContentFromInputStream(response.getEntity().getContent());
}
private static String getContentFromInputStream(InputStream is) throws IOException {
String line;
StringBuilder sb=new StringBuilder();
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
while((line=reader.readLine())!=null) {
sb.append(line);
}
reader.close();
return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我发送POST请求并获得响应.但在注册方法我使用俄语名称(西里尔文),并有"????? ???" 在我的服务器上.我该如何解决?我如何编码俄文?
Men*_*los 11
您需要将请求编码设置为UTF-8.
The request or response body can be any encoding, but by default is ISO-8859-1. The encoding may be specified in the Content-Type header, for example:
Content-Type: text/html; charset=UTF-8
Run Code Online (Sandbox Code Playgroud)
来自:http://hc.apache.org/httpclient-3.x/charencodings.html
如何实现这一目标的一个例子:
HttpClient httpclient = new HttpClient();
httpclient.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
Run Code Online (Sandbox Code Playgroud)
另外,我看到你的使用UrlEncodedFormEntity.您应该将编码添加到构造函数中,如下所示:
new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
Run Code Online (Sandbox Code Playgroud)
也许您读或写的答案是错误的?
确保在写入请求和读取请求以及post http headers中使用相同的编码。
要定义读取数据的编码,请使用InputStreamReader(InputStream, Charset)构造函数。
| 归档时间: |
|
| 查看次数: |
10289 次 |
| 最近记录: |