Java HttpClient请求参数乱码解决方案:指定UTF-8编码
//创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); //创建URIBuilder URIBuilder uriBuilder = new URIBuilder(System_Url.getOssDomain()+"/push/pushMessage.html"); //设置参数 uriBuilder.setParameter("pushFrequency","update"); uriBuilder.setParameter("categoryId",management.getId().toString()); uriBuilder.setParameter("categoryName",management.getName()); uriBuilder.setParameter("articleTitle",sysLaws.getLawsName()); //创建HttpGet对象,设置url访问地址 HttpGet httpGet = new HttpGet(uriBuilder.build()); CloseableHttpResponse response = null; try { //使用HttpClient发起请求,获取response response = httpClient.execute(httpGet); //解析响应 if (response.getStatusLine().getStatusCode() == 200) { String content = EntityUtils.toString(response.getEntity(), "utf8"); } } catch (IOException e) { e.printStackTrace(); }finally { //关闭response try { response.close(); } catch (IOException e) { e.printStackTrace(); } try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } 指定了utf-8编码 为什么本地运行参数不乱码,测试环境乱码内容:在本地运行时,可能使用的是默认的编码方式(如UTF-8),而测试环境可能使用的是其他的编码方式,导致参数乱码。需要确保在测试环境中使用的编码方式与本地环境一致,可以在代码中指定编码方式来解决该问题。
原文地址: https://www.cveoy.top/t/topic/pnDQ 著作权归作者所有。请勿转载和采集!