1. 程式人生 > >通過HttpClinet類用get方法獲得遠端介面返回的Json串

通過HttpClinet類用get方法獲得遠端介面返回的Json串

public class HttpClientUtil {
    public static String requestByGetMethod(String s) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        StringBuilder entityStringBuilder = null;
        try {
            HttpGet get = new HttpGet(s);
            CloseableHttpResponse httpResponse = null;
            httpResponse = httpClient.execute(get);
            try {
                HttpEntity entity = httpResponse.getEntity();
                entityStringBuilder = new StringBuilder();
                if (null != entity) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"), 8 * 1024);
                    String line = null;
                    while ((line = bufferedReader.readLine()) != null) {
                        entityStringBuilder.append(line + "/n");
                    }
                }
            } finally {
                httpResponse.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return entityStringBuilder.toString();
    }
}


public class TestUrl {
    public static void main(String args[]) {
        String url = "http://suggest.taobao.com/sug?code=utf-8&q=牛奶&callback=cb";
        String res = null;
        try {
            res = HttpClientUtil.requestByGetMethod(url);
            JSONObject result = new JSONObject();
            System.out.println(res);
            res = res.substring(res.indexOf("{"), res.indexOf("}") + 1);
            System.out.println(res);
            result = JSONObject.fromObject(res);
            String token = result.getString("result");
            System.out.println(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


用淘寶的商品搜尋介面搜尋“牛奶”的執行結果:

[["牛奶杯","194640"],["牛奶棉","61327"],["牛奶棉毛線","12855"],["牛奶洗面奶","10614"],["牛奶粉","236940"],["牛奶糖","49320"],["牛奶片","56362"],["牛奶1l","11292"],["牛奶棉線","7820"],["牛奶 1212","1600"]]