发布网友
共2个回答
热心网友
看下你post的方法,设置下这个
httpURLConnection.setRequestProperty("Charset", "utf-8");
拼接参数时:转一下格式
URLEncoder.encode(String.valueOf(value), "utf-8")
下面是我使用的POST方法,最简单的一种
Map<String, String> params = new HashMap<>(); //参数
热心网友
/**
* POST方式请求
*
* @param uri
* 服务器的uri要用物理IP或域名,不识别localhost或127.0.0.1形式!
* @param paramMap
* @param headers
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String post(String uri, Map<String, String> paramMap,
Map<String, String> headers) throws ClientProtocolException,
IOException {
HttpPost httpPost = new HttpPost(uri);
if (headers != null) {
for (String key : headers.keySet()) {
httpPost.setHeader(key, headers.get(key));
}
}
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (paramMap != null) {
for (String key : paramMap.keySet()) {
params.add(new BasicNameValuePair(key, paramMap.get(key)));
}
httpPost.setEntity(new ByteArrayEntity(paramMap.get("reqData").getBytes("UTF-8")));
//httpPost.setEntity(new UrlEncodedFormEntity(params,
//DEFAULT_ENCODING));
}
HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
int statusCode;
if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) {
return EntityUtils.toString(httpResponse.getEntity());
}
throw new IOException("status is " + statusCode);
}
public static String post(String uri, String contentType, String content)
throws Exception {
org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
PostMethod post = new PostMethod(uri);
RequestEntity entity = new StringRequestEntity(content, contentType,DEFAULT_ENCODING);
post.setRequestEntity(entity);
int statusCode = client.executeMethod(post);
if (statusCode == 200) {
return post.getResponseBodyAsString();
}
throw new IOException("status is " + statusCode);
}
你可以设置下他的默认传递代码方式:DEFAULT_ENCODING 为UTF-8