HttpURLConnection和HttpClient获取Json数据
来源:互联网 发布:linux telnet root登录 编辑:程序博客网 时间:2024/05/17 00:14
Android中提供的HttpURLConnection(JDK自带)和HttpClient(Apache提供)接口可以用来开发HTTP程序。
服务器端有如下json数据
- [
- {
- "image": "http://222.22.254.223:8080/web/a.jpg",
- "title": "新闻标题1",
- "content": "新闻内容1",
- "conut": "跟帖人数1"
- },
- {
- "image": "http://222.22.254.223:8080/web/b.jpg",
- "title": "新闻标题2",
- "content": "新闻内容2",
- "conut": "跟帖人数2"
- },
- {
- "image": "http://222.22.254.223:8080/web/c.jpg",
- "title": "新闻标题3",
- "content": "新闻内容3",
- "conut": "跟帖人数3"
- },
- {
- "image": "http://222.22.254.223:8080/web/d.jpg",
- "title": "新闻标题4",
- "content": "新闻内容4",
- "conut": "跟帖人数4"
- },
- {
- "image": "http://222.22.254.223:8080/web/e.jpg",
- "title": "新闻标题5",
- "content": "新闻内容5",
- "conut": "跟帖人数5"
- }
- ]
1.首先来看HttpURLConnection的Get方法获取json数据:
- public List<HeadNews> HttpURLConnection_GET()throws Exception{
- List<HeadNews>list=new ArrayList<HeadNews>();
- String path="http://222.22.254.223:8080/web/HeadNewsJson";
- //参数直接加载url后面
- path+="?username="+URLEncoder.encode("我是大帅哥HttpClientGET","utf-8");
- URL url=new URL(path);
- HttpURLConnection conn=(HttpURLConnection) url.openConnection();
- conn.setRequestMethod("GET");
- conn.setConnectTimeout(5000);
- if(conn.getResponseCode()==200){ //200表示请求成功
- InputStream is=conn.getInputStream(); //以输入流的形式返回
- //将输入流转换成字符串
- ByteArrayOutputStream baos=new ByteArrayOutputStream();
- byte [] buffer=new byte[1024];
- int len=0;
- while((len=is.read(buffer))!=-1){
- baos.write(buffer, 0, len);
- }
- String jsonString=baos.toString();
- baos.close();
- is.close();
- //转换成json数据处理
- JSONArray jsonArray=new JSONArray(jsonString);
- for(int i=0;i<jsonArray.length();i++){ //一个循环代表一个headnews对象
- HeadNews headnews=new HeadNews();
- JSONObject jsonObject = jsonArray.getJSONObject(i);
- headnews.setTitle(jsonObject.getString("title"));
- headnews.setContent(jsonObject.getString("content"));
- headnews.setConut(jsonObject.getString("conut"));
- headnews.setImage(jsonObject.getString("image"));
- list.add(headnews);
- }
- }
- return list;
- }
2.HttpURLConnection的POST方法获取json数据:
- public List<HeadNews>HttpURLConnection_POST() throws Exception{
- List<HeadNews>list=new ArrayList<HeadNews>();
- String path="http://222.22.254.223:8080/web/HeadNewsJson";
- URL url=new URL(path);
- HttpURLConnection conn=(HttpURLConnection) url.openConnection();
- conn.setDoOutput(true); //允许向服务器输出数据
- conn.setDoInput(true); //允许接收服务器数据
- conn.setRequestMethod("POST");
- conn.setUseCaches(false); // Post 请求不能使用缓存
- conn.setConnectTimeout(5000);
- // 参数前面不能加?号
- String urlParas="username="+URLEncoder.encode("admin", "UTF-8");
- byte [] entity=urlParas.getBytes();
- //设置请求参数
- conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); //实体参数类型
- conn.setRequestProperty("Content-Length", entity.length+""); //实体参数长度
- // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
- // 要注意的是connection.getOutputStream会隐含的进行connect。
- conn.connect();
- //将要上传的参数写入流中
- conn.getOutputStream().write(entity);
- if(conn.getResponseCode()==200){
- InputStream is=conn.getInputStream();
- //将输入流转换成字符串
- ByteArrayOutputStream baos=new ByteArrayOutputStream();
- byte [] buffer=new byte[1024];
- int len=0;
- while((len=is.read(buffer))!=-1){
- baos.write(buffer, 0, len);
- }
- String json=baos.toString();
- baos.close();
- is.close();
- //json处理
- JSONArray jsonArray=new JSONArray(json);
- for(int i=0;i<jsonArray.length();i++){
- HeadNews headnews=new HeadNews();
- JSONObject jsonObject = jsonArray.getJSONObject(i);
- headnews.setTitle(jsonObject.getString("title"));
- headnews.setContent(jsonObject.getString("content"));
- headnews.setConut(jsonObject.getString("conut"));
- headnews.setImage(jsonObject.getString("image"));
- list.add(headnews);
- }
- }
- return list;
- }
- public List<HeadNews>HttpClient_GET() throws Exception{
- List<HeadNews>list=new LinkedList<HeadNews>();
- String path="http://222.22.254.223:8080/web/HeadNewsJson";
- //get方法设置参数要?号
- StringBuilder sb=new StringBuilder(path);
- sb.append("?");
- sb.append("username=").append(URLEncoder.encode("我是大帅哥HttpClientGET","utf-8"));
- //1.得到浏览器
- HttpClient httpClient=new DefaultHttpClient();//浏览器
- //2指定请求方式
- HttpGet httpGet=new HttpGet(sb.toString());
- //3.执行请求
- HttpResponse httpResponse=httpClient.execute(httpGet);
- //4 判断请求是否成功
- int status=httpResponse.getStatusLine().getStatusCode();
- if(status==200){
- //读取响应内容
- String result=EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
- //json处理
- JSONArray jsonArray=new JSONArray(result);
- for(int i=0;i<jsonArray.length();i++){
- HeadNews headnews=new HeadNews();
- JSONObject jsonObject = jsonArray.getJSONObject(i);
- headnews.setTitle(jsonObject.getString("title"));
- headnews.setContent(jsonObject.getString("content"));
- headnews.setConut(jsonObject.getString("conut"));
- headnews.setImage(jsonObject.getString("image"));
- list.add(headnews);
- }
- }
- return list;
- }
4.使用HttpClient的post方法获取Json:
- public List<HeadNews>HttpClient_POST() throws Exception{
- List<HeadNews>list=new ArrayList<HeadNews>();
- String path="http://222.22.254.223:8080/web/HeadNewsJson";
- //1.得到浏览器
- HttpClient httpClient=new DefaultHttpClient();
- //2指定请求方式
- HttpPost httpPost=new HttpPost(path);
- //3.构建请求实体的数据
- List<NameValuePair> paras=new ArrayList<NameValuePair>();
- paras.add(new BasicNameValuePair("username", "我是帅哥httpclientPost"));
- //4.构建实体
- UrlEncodedFormEntity entity=new UrlEncodedFormEntity(paras,"utf-8");
- //5。。把实体放入请求对象
- httpPost.setEntity(entity);
- //6.执行请求
- HttpResponse httpResponse=httpClient.execute(httpPost);
- int status=httpResponse.getStatusLine().getStatusCode();
- if(status==200){
- //读取响应内容
- String result=EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
- //
- JSONArray jsonArray=new JSONArray(result);
- for(int i=0;i<jsonArray.length();i++){
- HeadNews headnews=new HeadNews();
- JSONObject jsonObject = jsonArray.getJSONObject(i);
- headnews.setTitle(jsonObject.getString("title"));
- headnews.setContent(jsonObject.getString("content"));
- headnews.setConut(jsonObject.getString("conut"));
- headnews.setImage(jsonObject.getString("image"));
- list.add(headnews);
- }
- }
- return list;
- }
另外提一点:
Get方式提交不论是HttpURLConnection还是HttpClient,传递中文参数会产生乱码,(传递方法看上面代码)
虽然已经用URLEncoder.encode("中文参数","utf-8")转成utf-8格式,在servlet端也使用spring过滤中文乱码,
但是仍然要这样子接收,不然会中文乱码(不知为何):
- new String(request.getParameter("username").getBytes("ISO-8859-1"),"UTF-8")
Post方式接收中文参数则没有这个问题,直接:
- request.getParameter("username")
原文出处:HttpURLConnection和HttpClient获取Json数据
0 0
- HttpURLConnection和HttpClient获取Json数据
- HttpURLConnection和HttpClient获取Json数据
- HttpURLConnection和HttpClient分别以GET和POST获取Json数据
- HttpClient和HttpUrlConnection实现post发送和接收json数据
- 获取网上数据的两种方法HttpURLConnection和HttpClient
- Android HttpURLConnection和HttpClient获取网络内容
- android HttpClient获取json数据
- HttpClient和HttpURLConnection网络请求数据
- HttpClient和HttpURLConnection网络请求数据
- Android HttpURLConnection数据获取并JSON解析
- Android用HttpURLConnection获取JSON数据
- HttpURLConnection和httpclient比较
- HttpURLConnection和HttpClient联网
- HttpURLConnection和HttpClient
- HttpURLConnection和HttpClient联网
- HttpURLConnection、HttpClient和Session
- HttpClient和HttpURLConnection比较
- HttpURLConnection和HttpClient区别
- Objective-C ,ios,iphone开发基础:JSON解析(使用苹果官方提供的JSON库:NSJSONSerialization)
- GEM5简介
- 回车与换行的区别
- 权力游戏“紫婚”毁誉参半 童话镇入佳境
- SPOJ 220 . Relevant Phrases of Annihilation(后缀数组)
- HttpURLConnection和HttpClient获取Json数据
- UVA The Mad Numerologist
- TI DSP库VLIB介绍
- ViewPager3D
- java的事件监听
- c++ 第二章 类的成员变量、函数
- Android开发之得到新打开Activity关闭后返回的数据
- 计算N级行列式
- iOS开发者有价值的工具集