2013-05-28 70 views
1

我需要調用Java中這項服務 -如何使用地圖創建查詢字符串? (JAVA)

https://api.semantics3.com/test/v1/products?q={"cat_id": "13658", "brand": "Toshiba", "model": "Satellite"} 

我已經成功地做到這一點在Python如下 -

class Semantics: 
    def __init__(self): 
     self.service_address = 'https://api.semantics3.com/test/v1/products?' 
     self.api_key = 'SEM3158A71D4AB3A3715C2230B96943F46D0' 
    def query(self, params): 
     query = 'q=' + params.__dict__.__str__().replace("'",'"') 
     query = urlencode(urlparse.parse_qs(query), True) 
     req = Request(url = self.service_address + query) 
     req.add_header('api_key', self.api_key)   
     return urlopen(req).read() 

class QueryParams: 
    def __init__(self, cat_id, model, brand): 
     self.cat_id = cat_id 
     self.model = model 
     self.brand = brand 

qp = QueryParams('13658', 'Satellite', "Toshiba") 
print Semantics().query(qp) 

我試圖寫的用Spring REST API等效的Java程序和Apache HttpClient無濟於事。我無法找到將字典(即Map)設置到查詢字符串中的方法。

public static void main(String[] args) { 
    String uri = "https://api.semantics3.com/test/v1/products?"; 

    HttpClient hc = new HttpClient(); 
    GetMethod method = new GetMethod(uri); 

    method.getParams().setParameter("q", "Toshiba");//How do I insert a Map here? 

    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
      new DefaultHttpMethodRetryHandler(3, false)); 

    method.setRequestHeader("api_key", "SEM2158A71D4AB3A3715C2435B96943F46D0");  
    try { 
     int statusCode = hc.executeMethod(method); 
     System.out.println(statusCode); 
     byte[] responseBody = method.getResponseBody(); 
     System.out.println(new String(responseBody)); 
    } catch (HttpException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     method.releaseConnection(); 
    } 
} 

在最低級別我可以手動手動經由級聯產生的查詢字符串,然後地址編碼。但是,有沒有更好的方法來做到這一點?

+0

你q的格式是JSON,你爲什麼不使用JSON Lib來獲取你的值? – Xavjer

回答

0

我想你可以使用外部的jar像GSONMap轉換成JSON

Map<String, String> map = new HashMap<String,String>(); 
map.put("cat_id", "12345"); 

..

Gson gson = new Gson(); 
method.getParams().setParameter("q", gson.toJson(map)); 
0

看一看Google's Http Client

正如你可以看到從examples,它使用對象來構建請求url並反序列化響應主體。 The docs也會告訴你如何專門解析JSON,並且你可以選擇你選擇的JSON庫。