其中的中文编码并不是在发送之前就将数据进行编码,而是在请求时进行设置的,不需要手动编码。
1、Hutool中
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import java.util.LinkedHashMap;
import java.util.Map;
public static void main(String[] args) throws Exception {
Map<String, Object> map = new LinkedHashMap<>();
;
map.put("param1", "1");
map.put("param2", "2");
map.put("param3", "3");
map.put("param4", "中文");
//设置表单数据的编码集
String params = HttpUtil.toParams(map, "GBK");
HttpRequest post = HttpUtil.createPost("url");
String body = post.body(params).execute().body();
System.out.println(body);
}
2、HttpClient中
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public static void main(String[] args) throws Exception {
String info = null;
try {
HttpClient httpclient = new HttpClient();
PostMethod post = new PostMethod("url");
post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "gbk");
post.addParameter("param1", "1");
post.addParameter("param2", "2");
post.addParameter("param3", "3");
post.addParameter("param4", "中文");
httpclient.executeMethod(post);
info = new String(post.getResponseBody(), "gbk");
System.out.println(info);
} catch (Exception e) {
e.printStackTrace();
}
}
3、Groovy中的HTTPBuilder
import groovyx.net.http.ContentType
import groovyx.net.http.EncoderRegistry
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method
static void main(String[] args) {
Map<String, Object> map = new LinkedHashMap<>();
map.put("param1", "1");
map.put("param2", "2");
map.put("param3", "3");
map.put("param4", "中文");
def data = null
def http = new HTTPBuilder("url")
http.ignoreSSLIssues()
//设置表单数据的编码集
http.setEncoderRegistry(new EncoderRegistry().setCharset("GBK"))
http.request(Method.POST, ContentType.TEXT) { req ->
requestContentType = ContentType.URLENC
uri.query = map
response.success = { resp, reader ->
data = reader.text
}
}
}
标签:编码,中文,http,map,表单,new,put,import,post
From: https://www.cnblogs.com/dyaqi/p/17930876.html