http請求經(jīng)常會遇到一些奇怪的問題,例如發(fā)送請求失敗,或者response出現(xiàn)問題,或者參數(shù)中帶了url調接口失敗,調用微信接口失敗,調用nginx轉發(fā)失敗,等等。
但用postman調用不會有問題。
這說明參數(shù)本身沒有問題,服務器也沒有問題,是客戶端的問題。在你的代碼里面,客戶端就是你調用的那些發(fā)http的包。例如httpclient。
通常都是body沒有設置字符集。
例如
HttpPost httpPost = new HttpPost(url);
StringEntity body = new StringEntity(jsonStr, "UTF-8");
httpPost.setEntity(body);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"UTF-8");
httpPost.setEntity(entity);
簡單說就是要給特殊字符編碼。body中的那些特殊字符需要編碼。有時是用
URLEncoder.encode(bodyStr, "UTF-8");
例如StringEntity的源碼:他將傳進來的body內容轉成byte數(shù)組。所以就無需URLEncoder。文章來源:http://www.zghlxwxcb.cn/news/detail-730719.html
但這里charset默認是ISO8859-1,所以需要指定UTF-8。文章來源地址http://www.zghlxwxcb.cn/news/detail-730719.html
public class StringEntity extends AbstractHttpEntity implements Cloneable {
protected final byte[] content;
public StringEntity(String string, ContentType contentType){
Charset charset = contentType != null ? contentType.getCharset() : null;
this.content = string.getBytes(charset);
}
}
到了這里,關于java中http請求,記得加字符集 UTF-8,StringEntity的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!