如何使用第三方服务API 您所在的位置:网站首页 如何使用百度地图语音导航定位 如何使用第三方服务API

如何使用第三方服务API

2024-02-15 08:16| 来源: 网络整理| 查看: 265

继上次篇博客介绍的HttpClient工具包发送请求,本文将简述一下如何在实际开发中使用http请求使用第三方的服务API。

上一篇博客地址:如何在项目中使用HttpClient工具包发送http请求_C.J.Y的博客-CSDN博客

        本文将通过使用百度地图的普通定位功能来讲解如何使用第三方服务API。先将使用HttpClient工具包发送http请求的操作流程封装成一个工具类,然后使用junit单元测试来给百度地图服务发送对应的请求来获取定位信息。

具体代码如下:

工具类代码:

package com.example.httpClient; import com.alibaba.fastjson.JSONObject; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.clienthods.HttpGet; import org.apache.http.clienthods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; public class HttpClientUtil { static final int TIMEOUT_MS = 5 * 1000; /** * 发送GET方式请求 * * @param url 请求地址 * @param paramMap 请求参数集合 * @return */ public static String getRequest(String url, Map paramMap) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); String response = ""; try { URIBuilder builder = new URIBuilder(url); if (paramMap != null) { for (String key : paramMap.keySet()) { builder.addParameter(key, paramMap.get(key)); } } URI uri = builder.build(); //创建GET请求 HttpGet httpGet = new HttpGet(uri); //发送请求 response = httpClient.execute(httpGet, httpResponse -> EntityUtils.toString(httpResponse.getEntity())); } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return response; } /** * 发送POST方式请求(请求参数为普通表单参数) * * @param url 请求地址 * @param paramMap 请求参数集合 * @return */ public static String postRequest(String url, Map paramMap) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); String response = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建参数列表 if (paramMap != null) { List paramList = new ArrayList(); for (Map.Entry param : paramMap.entrySet()) { paramList.add(new BasicNameValuePair(param.getKey(), param.getValue())); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); httpPost.setEntity(entity); } // 自定义连接超时时间并配置 httpPost.setConfig(builderRequestConfig()); // 执行http请求 response = httpClient.execute(httpPost, httpResponse -> EntityUtils.toString(httpResponse.getEntity())); } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return response; } /** * 发送POST方式请求(请求参数为JSON类型参数) * * @param url 请求地址 * @param paramMap 请求参数集合 * @return */ public static String postJsonRequest(String url, Map paramMap) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); String response = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); if (paramMap != null) { //构造json格式数据 JSONObject jsonObject = new JSONObject(); for (Map.Entry param : paramMap.entrySet()) { jsonObject.put(param.getKey(), param.getValue()); } StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8"); //设置请求编码 entity.setContentEncoding("utf-8"); //设置数据类型 entity.setContentType("application/json"); httpPost.setEntity(entity); } // 自定义连接超时时间并配置 httpPost.setConfig(builderRequestConfig()); // 执行http请求 response = httpClient.execute(httpPost, httpResponse -> EntityUtils.toString(httpResponse.getEntity())); } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return response; } //设置连接超时时间 private static RequestConfig builderRequestConfig() { return RequestConfig.custom() .setConnectTimeout(TIMEOUT_MS) .setConnectionRequestTimeout(TIMEOUT_MS) .setSocketTimeout(TIMEOUT_MS).build(); } }

        在此工具类的基础上,只需要选择对应的静态方法并传入请求地址和请求参数集合即可将结果返回。

        

        要想使用百度地图的定位功能,就必须根据百度地图提供的服务文档发请求。服务文档地址:Web服务API | 百度地图API SDK

         根据文档我们可以知道请求地址和请求参数,请求参数分为可选和必填两种,根据需要选中填写请求参数。使用简单的ip定位只需要把必填的ak参数传递过去即可得到返回值。

         文档中也记录了返回值格式是JSON格式,因此我们得到的返回值会是一个JSON格式的字符串,只需要使用JSON的解析工具包fastjson就可以快速解析出结果。

具体实现代码:

package com.example.baidu; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.example.httpClient.HttpClientUtil; import org.junit.Test; import java.util.HashMap; import java.util.Map; public class MapTest { //百度地图定位的请求地址 public static String URL = "https://api.map.baidu.com/location/ip?"; public static String ak = "注册成为百度用户,然后申请为地图开放平台开发者就可以获得密钥AK"; @Test public void test() { Map map = new HashMap(); map.put("ak",ak); //发送get请求 String json = HttpClientUtil.getRequest(URL, map); //解析结果 JSONObject result = JSON.parseObject(json); System.out.println("\n result = "+result); JSONObject content = result.getJSONObject("content"); System.out.println("\n content = "+content); String address = content.getString("address"); System.out.println("\n address = "+address); JSONObject address_detail = content.getJSONObject("address_detail"); System.out.println("\n address_detail = "+address_detail); } }

结果展示:



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有