2013-07-17 39 views
4

我使用下面的代码来获取经纬度。长。通过提供MCC,MNC 我正在使用Google Maps地理位置API,但对于不同的MCC/MNC值,我得到了相同的结果(纬度/经度)。即使当我要求空白json时,我也会得到相同的结果(lat/long)。 我哪里错了?使用谷歌地图地理定位API

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

    } 

} 

回答

1

您的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/

+0

同时在“callID”的拼写中存在错误,它应该是callId。 – Tushar

3

它看起来像问题是在这里的是,HttpPost对象默认发送其参数x-www-form-urlencoded,但你需要它作为发送application/json。这个线程解释了如果你这样做会发生什么:How to use parameters with HttpPost

有几种方法可以解决它。一个是设置Content-type头的HttpPost对象上:

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

其他的,我认为这是更好的,是使用StringEntity的的setContentType方法记载here

entity.setContentType("application/json"); 

无论是哪种在发送请求之前使用的单行应该可以解决问题。

+0

我试过,但它可是我得到相同的输出。 – Tushar