问题
- 需要调用第三方接口发送短信,必须使用
post
方法,请求和返回都是JSON
格式数据,编码要求UTF-8
- 项目中已有的 HttpUtil 工具类中,有
post
方法,但是请求此接口没有任何返回;使用curl
发送post
请求,有数据返回,说明接口没问题 - 看了下对方接口文档,要求
json
,应该是需要将json
数据放入请求体,只好再加一个post
方法了。 - 重新写了个新方法后,接口能正常访问了。但是新问题来了,中文乱码。明明设置
UTF-8
,还是不行。下面说下解决方法,并贴上代码。
解决
- 首先思路要明确,
post
无数据返回,应该是没遵守对方的接口要求,果断将json格式数据放入请求体,第一个问题解决。 - 中文乱码,肯定是编码格式问题。虽然设置了
UTF-8
,但肯定是没设置好。看了下源码,果然是代码写的有问题。
public static JSONObject doPost(String url, JSONObject json){
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
JSONObject response = null;
try {
StringEntity s = new StringEntity(json.toString(),"UTF-8");
s.setContentType("application/json");
post.setEntity(s);
HttpResponse res = httpclient.execute(post);
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
String result = EntityUtils.toString(res.getEntity());
response = JSONObject.parseObject(result);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
logger.info("执行HTTP Post请求" + url + "时,结果:{}", response);
return response;
}
探究
- 由于短信接口有可信
ip
限制,必须在服务器上测试,使用curl提交post请求
很方便,很实用,需要的可以拿走参考。
curl -H "Content-Type: application/json" -X POST -d '{"senderSystem": "xxx", "authCode":"xxx", "receiverUser":"111", "msgType":"2","content":中文内容" }' "http://xxx:xx/xxx/message/send"
- 针对乱码问题,主要是
StringEntity
类的2个不同的构造器,起不同的作用 - 构造器
StringEntity(String string)
使用的是默认编码Consts.ISO_8859_1
,在new
创建对象时,数据已经被转码了,后面再设置UTF-8
也没有用了。 - 构造器
StringEntity(String string, String charset)
会根据传递的编码格式转码,所以结果符合自己需求。
public StringEntity(String string, String charset) throws UnsupportedCharsetException {
this(string, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), charset));
}
public StringEntity(String string) throws UnsupportedEncodingException {
this(string, ContentType.DEFAULT_TEXT);
}
static {
APPLICATION_ATOM_XML = create("application/atom+xml", Consts.ISO_8859_1);
APPLICATION_FORM_URLENCODED = create("application/x-www-form-urlencoded", Consts.ISO_8859_1);
APPLICATION_JSON = create("application/json", Consts.UTF_8);
APPLICATION_OCTET_STREAM = create("application/octet-stream", (Charset)null);
APPLICATION_SVG_XML = create("application/svg+xml", Consts.ISO_8859_1);
APPLICATION_XHTML_XML = create("application/xhtml+xml", Consts.ISO_8859_1);
APPLICATION_XML = create("application/xml", Consts.ISO_8859_1);
MULTIPART_FORM_DATA = create("multipart/form-data", Consts.ISO_8859_1);
TEXT_HTML = create("text/html", Consts.ISO_8859_1);
TEXT_PLAIN = create("text/plain", Consts.ISO_8859_1);
TEXT_XML = create("text/xml", Consts.ISO_8859_1);
WILDCARD = create("*/*", (Charset)null);
DEFAULT_TEXT = TEXT_PLAIN;
DEFAULT_BINARY = APPLICATION_OCTET_STREAM;
}