通过HttpClinet类用get方法获得远程接口返回的Json串

时间:2023-01-05 12:57:12



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"]]