2013-07-17 37 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