发送HTTP请求,调取第三方接口及返回数据的解析获取

发送HTTP请求,调取第三方接口

这是在做一个项目的时候需要调取三方接口获取数据的时候用到的来分享一下:

  1. application/x-www-form-urlencoded 方式
	/**
	 * 发送http POST请求
	 * @param   parameter为请求参数
	 * @return 远程响应结果
	 */
	public static String sendPunlic2GPost(String parameter) {
		log.info("--------begin--------");
		// 发送请求的URL
		String url = "请求地址";
		// 编码格式
		String charset = "UTF-8";
		// 请求内容
		String content = parameter;
		log.info(content);
		// 使用帮助类HttpClients创建CloseableHttpClient对象.
		CloseableHttpClient client = HttpClients.createDefault();
		// HTTP请求类型创建HttpPost实例
		HttpPost post = new HttpPost(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000)
				.setSocketTimeout(5000).build();
		post.setConfig(requestConfig);
		// 使用addHeader方法添加请求头部,诸如User-Agent, Accept-Encoding等参数.
		//请求中的媒体类型--
		post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
		// 组织数据
		StringEntity se;
		String resData = null;
		try {
			se = new StringEntity(content);
			// 设置编码格式
			se.setContentEncoding(charset);
			// 设置数据类型
			se.setContentType("application/json");
			// 对于POST请求,把请求体填充进HttpPost实体.
			post.setEntity(se);
			// 通过执行HttpPost请求获取CloseableHttpResponse实例
			// ,从此CloseableHttpResponse实例中获取状态码,错误信息,以及响应页面等等.
			CloseableHttpResponse response;
			try {
				response = client.execute(post);
				// 通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理?
				HttpEntity entity = response.getEntity();
				resData = EntityUtils.toString(response.getEntity());
				System.out.println(resData);
				// 最后关闭HttpClient资源.
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		log.info("--------end--------");
		//返回的数据资源
		return resData;
	}
  1. application/json;charset=UTF-8
    将上述中的 -请求中的媒体类型-这步修改为:
    post.setHeader(“Content-Type”, “application/json;charset=UTF-8”); 即可

  2. 返回值的解析获取:

String resData = sendPunlic2GPost(String parameter);
JSONObject jsStr = JSONObject.parseObject(operateDeviceOpen);
code = jsStr.getString("code");
//以此内推获取所需要返回的值

二更:
上面可以看到返回的json字符串转为了json对象,下面说说json字符串转为Java对象

方式1:

public static <T> T string2Obj(String str, Class<T> clazz){
    if(StringUtils.isEmpty(str) || clazz == null){
        return null;
    }

    try {
        return clazz.equals(String.class)? (T)str : objectMapper.readValue(str, clazz);
    } catch (Exception e) {
        log.warn("Parse String to Object error",e);
        return null;
    }
}

基本类型转换:

@Test
public void string2Obj() throws Exception {
    String str = "{\"name\":\"name\",\"age\":10,\"profileImageUrl\":\"link\"}";
    Student student = JsonUtil.string2Obj(str, Student.class);
    // Student(name=name, age=10, profileImageUrl=link)
    System.out.println(student);
}

各种复杂类型的转换,示例1:

public void string2Obj1() throws Exception {

    Student student1 = new Student();
    student1.setAge(10);
    student1.setName("name1");
    student1.setProfileImageUrl("link1");

    Student student2 = new Student();
    student2.setAge(20);
    student2.setName("name2");
    student2.setProfileImageUrl("link2");

    List<Student> studentList = new ArrayList<>();
    studentList.add(student1);
    studentList.add(student2);
    String result = JsonUtil.obj2String(studentList);
    // [{"name":"name1","age":10,"profileImageUrl":"link1"},{"name":"name2","age":20,"profileImageUrl":"link2"}]
    System.out.println(result);

    List<Student> finalList = JsonUtil.string2Obj(result, List.class);
    // [{name=name1, age=10, profileImageUrl=link1}, {name=name2, age=20, profileImageUrl=link2}]
    System.out.println(finalList);
}

复杂类型的转换,示例2:

public void string2Obj2() throws Exception {

    Map<String, List<Integer>> testMap = new HashMap<>();
    testMap.put("1", Arrays.asList(1, 2, 3));
    testMap.put("2", Arrays.asList(2, 3, 4));

    String result = JsonUtil.obj2String(testMap);
    // {"1":[1,2,3],"2":[2,3,4]}
    System.out.println(result);

    Map<String, List<Integer>> finalMap = JsonUtil.string2Obj(result, Map.class);
    // {1=[1, 2, 3], 2=[2, 3, 4]}
    System.out.println(finalMap);
}

可以用这3个函数进行序列化和反序列化操作

/** 将对象转为json */
public static <T> String obj2String(T obj) 

/** 将对象转为json,并格式化显示 */
public static <T> String obj2StringPretty(T obj)

/** 将json转为对象 */
public static <T> T string2Obj(String str, Class<T> clazz)

上面3个函数完全能满足你的需求,这里演示一下:

public void string2Obj3() throws Exception {

    Student student1 = new Student();
    student1.setAge(10);
    student1.setName("name1");
    student1.setProfileImageUrl("link1");

    Student student2 = new Student();
    student2.setAge(20);
    student2.setName("name2");
    student2.setProfileImageUrl("link2");

    List<Student> studentList = new ArrayList<>();
    studentList.add(student1);
    studentList.add(student2);
    String result = JsonUtil.obj2String(studentList);
    // [{"name":"name1","age":10,"profileImageUrl":"link1"},{"name":"name2","age":20,"profileImageUrl":"link2"}]
    System.out.println(result);

    List<Student> finalList = JsonUtil.string2Obj(result, new TypeReference<List<Student>>() {});
    // [{name=name1, age=10, profileImageUrl=link1}, {name=name2, age=20, profileImageUrl=link2}]
    System.out.println(finalList);
}
public void string2Obj4() throws Exception {

    Student student1 = new Student();
    student1.setAge(10);
    student1.setName("name1");
    student1.setProfileImageUrl("link1");

    Student student2 = new Student();
    student2.setAge(20);
    student2.setName("name2");
    student2.setProfileImageUrl("link2");

    List<Student> studentList = new ArrayList<>();
    studentList.add(student1);
    studentList.add(student2);
    String result = JsonUtil.obj2String(studentList);
    // [{"name":"name1","age":10,"profileImageUrl":"link1"},{"name":"name2","age":20,"profileImageUrl":"link2"}]
    System.out.println(result);

    List<Student> finalList = JsonUtil.string2Obj(result, List.class, Student.class);
    // [{name=name1, age=10, profileImageUrl=link1}, {name=name2, age=20, profileImageUrl=link2}]
    System.out.println(finalList);
}

你可能感兴趣的:(Java)