httpclient get和post,中文乱码已解决
来源:互联网 发布:appstore付费软件 编辑:程序博客网 时间:2024/04/30 08:58
使用httpclient方法
get:
使用get请求,获取url传过来的数据
得到的entity,一定要限定编码// 打印响应内容 ,转换为utf-8格式,避免所传内容包含汉字乱码context = EntityUtils.toString(entity, "UTF-8");
实例:
post:/*** 发送 get请求*/public String get(String url1) {CloseableHttpClient httpclient = HttpClients.createDefault();String context="";try {URL url = new URL(url1);URI uri = new URI(url.getProtocol(), url.getHost() + ":" + url.getPort(),url.getPath(), url.getQuery(), null);// 创建httpget.HttpGet httpget = new HttpGet(uri);System.out.println("executing request " + httpget.getURI());// 执行get请求.CloseableHttpResponse response = httpclient.execute(httpget);// 获取响应实体HttpEntity entity = response.getEntity();System.out.println("--------------------------------------");// 打印响应状态System.out.println(response.getStatusLine());if (entity != null) {// 打印响应内容 ,转换为utf-8格式,避免所传内容包含汉字乱码context = EntityUtils.toString(entity, "UTF-8");System.out.println(context);}response.close();return context;} catch (Exception e) {e.printStackTrace();return "Exception";}finally {// 关闭连接,释放资源try {httpclient.close();} catch (IOException e) {e.printStackTrace();}}}
post数据给URL,并获得其返回数据
除了接收到的数据要注意编码之外,post给URL的数据也要注意编码问题
tringEntityse=newStringEntity(param.toString(),"UTF-8");//解决传送的Json中文乱码
实例:
/*** 发送 post请求访问本地应用并根据传递参数不同返回不同结果*/public String post(String url,JSONObject param) {String context="";// 创建默认的httpClient实例.CloseableHttpClient httpclient = HttpClients.createDefault();try {URL url1 = new URL(url);URI uri = new URI(url1.getProtocol(), url1.getHost(), url1.getPath(), url1.getQuery(), null);// 创建httppostHttpPost httppost = new HttpPost(uri);// 绑定到请求 EntryStringEntity se = new StringEntity(param.toString() ,"UTF-8");//解决传送的Json中文乱码httppost.setEntity(se);// 发送请求CloseableHttpResponse response = httpclient.execute(httppost);// 得到应答的字符串,这也是一个 JSON 格式保存的数据HttpEntity entity = response.getEntity();if (entity != null) {context = EntityUtils.toString(entity, "UTF-8");}response.close();return context;} catch (Exception e) {e.printStackTrace();return "Exception";} finally {// 关闭连接,释放资源try {httpclient.close();} catch (IOException e) {e.printStackTrace();}}}}
0 0
- httpclient get和post,中文乱码已解决
- HttpClient使用post和get时Json中文乱码解决方案
- post/get解决中文乱码
- Servlet中文乱码原因 解决 Get 和 Post 和客户端
- Servlet中文乱码原因 解决 Get 和 Post 和客户端
- struts2解决get和post方式中文乱码
- 解决Get和Post请求中中文乱码问题
- 解决Get和post请求中中文乱码问题
- servlet中get和post的中文乱码解决
- 过滤器解决get和post方式提交的中文乱码
- 解决Get和Post请求中文乱码的问题
- GET请求中文乱码问题--已解决
- GET&POST方式解决中文乱码问题
- get post 中文请求乱码解决方式
- 解决post、get提交中文乱码问题
- springMVC解决post、get中文乱码
- HttpClient Get和Post
- post和get请求中文乱码解决方案
- SpringMVC控制器接收不了PUT提交的参数的解决方案
- struts.xml配置详解
- Windows中安装Laravel 5.1.x
- 关于委托。
- 《剑指offer》-二叉树中和为某一值的路径
- httpclient get和post,中文乱码已解决
- hdoj 2049 不容易系列之(4)——考新郎 【排列组合+全排列】
- 图像旋转与缩放
- Spark 内存架构
- UIWebView的一个简单实现
- iOS quartzCore第九章—— CoreAnimation
- 以C程序为例内存分布详解
- Yii2教程学习 - 博客地址迁移
- matlab2014a软件使用技巧 在命令行输入多行代码