簡體   English   中英

使用Google Maps Geolocation API

[英]Using The Google Maps Geolocation API

我正在使用以下代碼來獲取lat。 長。 通過提供MCC,MNC,我正在使用Google Maps Geo-location API,但我得到的結果(緯度/經度)與不同的MCC / MNC值相同。 即使我要求空白的json,我也得到相同的結果(lat / long)。 我哪里錯了?

public class CellID {

    public static void main(String[] args) {
        try{
            putDataToServer("https://www.googleapis.com/geolocation/v1/geolocate?key=mykey",null);
        }
        catch(Throwable throwable){
            System.out.println("Error");
        }
    }

    public static String putDataToServer(String url,JSONObject returnedJObject) throws Throwable
    {

        HttpPost request = new HttpPost(url);

        JSONStringer json = (JSONStringer) new JSONStringer()
        .object() 
         .key("mobileCountryCode").value(504)   
         .key("mobileNetworkCode").value(0)
         .key("locationAreaCode").value(0)
         .key("cellID").value(0)
        .endObject();



        System.out.println("json"+json.toString());

        StringEntity entity = new StringEntity(json.toString(), "UTF-8");


                 request.setEntity(entity); 


        HttpResponse response =null;
        HttpClient httpClient = new DefaultHttpClient();

        try{

            response = httpClient.execute(request); 
        }
        catch(SocketException se)
        {
            throw se;
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        //Displaying the response received.
        String line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
            if (line.startsWith("Auth=")) {
                String key = line.substring(5);
                // Do something with the key
            }

        }
        return response.getEntity().toString();

    }

}

看起來問題在於HttpPost對象默認將其參數發送為x-www-form-urlencoded ,但您需要將其作為application/json發送。 該線程解釋了如果執行此操作會發生什么: 如何使用HttpPost參數

有幾種方法可以解決它。 一種是在HttpPost對象上設置Content-type標頭:

request.setHeader("Content-type", "application/json");

另一個,我認為更好,是使用此處記錄的StringEntity的setContentType方法

entity.setContentType("application/json");

在發送請求之前使用這些單行中的任何一行都應該解決問題。

您的JSON請求對象是否完整? 我的意思是它看起來像你正在使用的鍵是單個“塔”描述的一部分,但這只是更大的請求體的一部分,應該格式化為:

{
  "homeMobileCountryCode": 310,
  "homeMobileNetworkCode": 410,
  "radioType": "gsm",
  "carrier": "Vodafone",
  "cellTowers": [
   // See the Cell Tower Objects section below.
  ],
  "wifiAccessPoints": [
    // See the WiFi Access Point Objects section below.
  ]
}

塔對象的格式如下:

{'cellTowers': [
  {
    'cellId': 42,
    'locationAreaCode': 415,
    'mobileCountryCode': 310,
    'mobileNetworkCode': 410,
    'age': 0,
    'signalStrength': -60,
    'timingAdvance': 15
  }
]}

我想我錯過了你的json對象如何變成完整的對象?

https://developers.google.com/maps/documentation/business/geolocation/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM