首页 > 技术文章 > HttpClient 发送 post 请求中文全是问号

duniqb 2019-11-22 19:12 原文

 

使用 HttpClient 发送 post 请求,但发出去的请求体里的英文正常,中文全是问号,需要设置以下

HttpClient client = HttpClients.createDefault();

        // 构造 POST 参数
        ArrayList<NameValuePair> postData = new ArrayList<>();
        postData.add(new BasicNameValuePair("username", "name"));
        postData.add(new BasicNameValuePair("pwd", "pwd"));

        HttpPost post = new HttpPost("http://xxx.xx.com");
        // 首先Header部分需要设定字符集为:uft-8
        post.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
		// 此处也需要设定
        post.setEntity(new UrlEncodedFormEntity(postData, "utf-8"));
        post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        post.setHeader("Accept-Encoding", "gzip, deflate");
        post.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
        post.setHeader("Connection", "keep-alive");
        post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36");
		// 执行请求
        HttpResponse response = client.execute(post);

这样,发出去的中文参数便正常了

推荐阅读