JSON数据解析、HttpClient请求、HashSet

3.2 JSON解析

3.2.1 Json数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
  "paramz": {
    "feeds": [
      {
        "id": 299076,
        "oid": 288340,
        "category": "article",
        "data": {
          "subject": "荔枝新闻3.0:不止是阅读",
          "summary": "江苏广电旗下资讯类手机应用“荔枝新闻”于近期推出全新升级换代的3.0版。",
          "cover": "/Attachs/Article/288340/3e8e2c397c70469f8845fad73aa38165_padmini.JPG",
          "pic": "",
          "format": "txt",
          "changed": "2015-09-22 16:01:41"
        }
      }
    ],
    "PageIndex": 1,
    "PageSize": 20,
    "TotalCount": 53521,
    "TotalPage": 2677
  }
}

  

3.2.2 解析JSON数据代码

复制代码
public class JsonUtils {

    /**
     * 根据json数据解析返回一个List<HashMap<String, Object>>集合
     * @param json  json数据
     * @return
     */
    public static List<HashMap<String, Object>> getJsonList(String json) {
        List<HashMap<String, Object>> dataList;
        dataList = new ArrayList<>();
        try {
            JSONObject rootObject = new JSONObject(json);
            JSONObject paramzObject = rootObject.getJSONObject("paramz");
            JSONArray feedsArray = paramzObject.getJSONArray("feeds");
            for (int i = 0; i < feedsArray.length(); i++) {
                JSONObject sonObject = feedsArray.getJSONObject(i);
                JSONObject dataObject = sonObject.getJSONObject("data");
                String subjectStr = dataObject.getString("subject");
                String summaryStr = dataObject.getString("summary");
                String coverStr = dataObject.getString("cover");
                HashMap<String, Object> map = new HashMap<>();
                map.put("subject", subjectStr);
                map.put("summary", summaryStr);
                map.put("cover", coverStr);
                dataList.add(map);
            }
            return dataList;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}
复制代码

3.2.3 List<Map<>> 转化为JSONArray

 //将List转为JSONArray
JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(arrayList));
System.out.println(jsonArray);

3.2.4 String 转化为JSONObject

String json = "{"abc":"1","hahah":"2"}";
JSONObject jsonObject = JSONObject.parseObject(content);

3.2.5 Map<> 转化为JSONObject

Map<String, Object> params = new HashMap<>();
SONObject json = new JSONObject(params);

3.3 HashSet

HashSet<Object> set = new HashSet<>();
set.add(map);

3.4 HttpClient

responseContent = EntityUtils.toString(httpEntity, "UTF-8");
复制代码
get请求:
    
 /**
     * 请求token
     * @return
     */
    private static String requestToken() {
        String result = "";
        DefaultHttpClient httpClient = new DefaultHttpClient();
        /* ***** 1. 请求 */
        HttpGet get = new HttpGet(apiURL+"?"+appId+"&"+appSecret);
        /* ****** 2. 请求结束,返回结果 */
        HttpResponse res = null;
        try {
            res = httpClient.execute(get);
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        /* 服务器成功地返回响应 */
        HttpEntity httpEntity = res.getEntity();
        /* 响应内容 */
        String responseContent = null;
        try {
            responseContent = EntityUtils.toString(httpEntity, "UTF-8");
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        /* 将响应内容转化为json对象 */
        JSONObject json = JSONObject.parseObject(responseContent);

        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            JSONObject data = json.getJSONObject("data");
            result = data.getString("token");
            //添加有效时间
            long expire = Long.parseLong(data.getString("expire"));
            long currentTimeMillis = System.currentTimeMillis();
            map.put("effectTime",Long.toString(expire+currentTimeMillis));
        }
        /* 关闭连接 ,释放资源 */
        httpClient.getConnectionManager().shutdown();
        return result;
    }
复制代码
复制代码
post请求:
    
package cn.itcast.crawler.test;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpPostTest {
    public static void main(String[] args)  {
        //1.创建HttpClient对象
        //DefaultHttpClient httpClient = new DefaultHttpClient();
          CloseableHttpClient httpClient= HttpClients.createDefault();
          //2.创建HttpPost对象,设置URL地址
        HttpPost httpPost=new HttpPost("http://www.itcast.cn");;
        //使用httpClient发起响应获取repsonse
        CloseableHttpResponse response=null;
        try {
            //res = httpClient.execute(post);
            response=httpClient.execute(httpPost);
            //4.解析响应,获取数据
            //*************判断状态码是否是200**********
            if(response.getStatusLine().getStatusCode()==200){
                HttpEntity httpEntity=response.getEntity();
                String content=EntityUtils.toString(httpEntity,"utf8");
                System.out.println(content.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
复制代码

示例代码:

复制代码
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/*
 * 利用HttpClient进行post请求的工具类
 */
public class HttpClientUtil {
    public String doPost(String url,Map<String,String> map,String charset){
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator iterator = map.entrySet().iterator();
            while(iterator.hasNext()){
                Entry<String,String> elem = (Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
            }
            if(list.size() > 0){
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
                httpPost.setEntity(entity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }
}


import java.util.HashMap;
import java.util.Map;
//对接口进行测试
public class TestMain {
    private String url = "https://192.168.1.101/";
    private String charset = "utf-8";
    private HttpClientUtil httpClientUtil = null;
    
    public TestMain(){
        httpClientUtil = new HttpClientUtil();
    }
    
    public void test(){
        String httpOrgCreateTest = url + "httpOrg/create";
        Map<String,String> createMap = new HashMap<String,String>();
        createMap.put("authuser","*****");
        createMap.put("authpass","*****");
        createMap.put("orgkey","****");
        createMap.put("orgname","****");
        String httpOrgCreateTestRtn = httpClientUtil.doPost(httpOrgCreateTest,createMap,charset);
        System.out.println("result:"+httpOrgCreateTestRtn);
    }
    
    public static void main(String[] args){
        TestMain main = new TestMain();
        main.test();
    }
}
复制代码

 

posted @   湘summer  阅读(158)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示