public String getRequestBody(WifiInfo[] wifiInfos) {
try { JSONObject request = new JSONObject(); request.put("boottime", SystemClock.elapsedRealtime() * 1000); request.put("indoorMode", 0); JSONArray infos = new JSONArray(); for (int i = 0; i < wifiInfos.length; i++) { JSONObject wifiInfo = new JSONObject(); wifiInfo.put("mac", wifiInfos[i].getMacAddress()); wifiInfo.put("rssi", wifiInfos[i].getRssi()); wifiInfo.put("time", SystemClock.elapsedRealtime() * 1000); infos.put(wifiInfo); } request.put("wifiInfos", wifiInfos); return request.toString(); } catch (JSONException e) { e.printStackTrace(); return ""; } } 3.请求网络定位 private String getNetworkLocation(String body, String apiKey) { HttpClient httpClient = new HttpClient.Builder().readTimeout(5000).connectTimeout(5000).build(); Request.Builder requestBuilder = httpClient.newRequest().url("https://locationapi.cloud.huawei.com/networklocation/v1/geoLocation").method("POST"); // 设置Request Header requestBuilder.addHeader("Authorization", "Bearer " + apiKey); requestBuilder.addHeader("Content-Type", "application/json"); requestBuilder.requestBody(new RequestBody() { @Override public String contentType() { return "application/json"; } @Override public void writeTo(OutputStream outputStream) throws IOException { outputStream.write(body.getBytes(Charset.defaultCharset())); outputStream.flush(); } }); try { Response<ResponseBody> response = httpClient.newSubmit(requestBuilder.build()).execute(); if (response.getCode() == 200) { InputStream is = response.getBody().getInputStream(); ByteArrayOutputStream message = new ByteArrayOutputStream(); int len = 0; byte[] buffer = new byte[1024]; while ((len = is.read(buffer)) != -1) { message.write(buffer, 0, len); } is.close(); message.close(); return new String(message.toByteArray(), Charset.defaultCharset()); } } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } return null; } 开发效果 编译安装完成后,连接Wi-Fi,开启应用,就可以仅通过网络定位得到用户的位置,结果如下。 { "indoor": 0, "errorCode": "0", "position": { "acc": 14.400121, "bearing": 0.0, "floorAcc": 0, "flags": 17, "lon": 113.86621570429958, "speed": 0.0, "mode": 0, "time": 0, "floor": 0, "indoorFlag": 0, "lat": 22.881333903191347 }, "locateType": "Wifi", "extraInfo": { "wifiExtraInfo": { "resultCode": 0, "macDetails": [ 0, 1, 2 ], "extraPosition": { "acc": 23.040194, "bearing": 0.0, "flags": 17, "lon": 113.86621570429958, "speed": 0.0, "mode": 0, "lat": 22.881333903191347 } } }, "errorMsg": "Success" }1、 数据来源于第三方报告