使用谷歌地图地理定位 API

4

我正在使用以下代码通过提供MCC和MNC来获取经纬度信息。我正在使用Google Maps地理位置API,但是对于不同的MCC/MNC值,我得到的结果(经纬度)是相同的。即使我请求空白的JSON,我仍然得到相同的结果(经纬度)。我错在哪里了?

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();

    }

}

你能提供一下你在代码中使用的导入吗,@Tushar? - BugsForBreakfast
2个回答

3
似乎问题在于HttpPost对象默认将其参数发送为“x-www-form-urlencoded”,但您需要将其发送为“application/json”。此线程解释了这样做会发生什么:如何使用HttpPost参数
有几种方法可以解决这个问题。其中一种是在HttpPost对象上设置Content-type头:
request.setHeader("Content-type", "application/json");

另一种更好的方法是使用StringEntity的setContentType方法,该方法在此处有文档记录。
entity.setContentType("application/json");

在发送请求之前使用这两行中的任意一行应该可以解决问题。


1
你的JSON请求对象完整吗?我的意思是,看起来你正在使用的键是单个“tower”描述的一部分,但这只是更大请求主体的一部分,应该格式化为:
{
  "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/


还有一个拼写错误,"callID" 应该是 callId。 - Tushar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接