문제

I need to call this service in Java -

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

I've managed to do this in python as follows -

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)

I have tried writing an equivalent Java program using Spring REST API and Apache HttpClient to no avail. I can't find a way to set a dictionary (i.e. Map) into the query String.

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

At the lowest level I can manually produce the query string manually via concatenation and then Url encode it. But is there a more elegant way to do it?

도움이 되었습니까?

해결책

I think you can use external jar like GSON to convert the Map into 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));

다른 팁

Have a look at Google's Http Client

As you can see from the examples, it uses objects to build the request url and deserialise the response body. The docs also show you how to deserialise JSON specifically, and you can choose your JSON library of choice.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top