如何创建带有地图的查询字符串? (JAVA)

时间:2013-05-28 10:25:40

标签: java python apache-commons-httpclient

我需要用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 APIApache HttpClient编写等效的Java程序无济于事。我找不到将字典(即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();
    }
}

在最低级别,我可以通过连接手动生成查询字符串,然后对其进行Url编码。但有更优雅的方式吗?

2 个答案:

答案 0 :(得分:0)

我认为您可以使用GSON之类的外部jar将Map转换为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));

答案 1 :(得分:0)

查看Google's Http Client

examples可以看出,它使用对象构建请求URL并反序列化响应主体。 The docs还向您展示了如何专门反序列化JSON,并且您可以选择您选择的JSON库。