如何用Java调用别人API接口

发布网友 发布时间:2022-04-23 01:45

我来回答

2个回答

热心网友 时间:2023-10-02 21:16

java发一个http请求过去,带上参数就可以了啊,跟我们在浏览器上访问资源是一样的 只是它返回的是json格式的数据而已
给你两个方法吧:
public static String do_post(String url, List<NameValuePair> name_value_pair) throws IOException {
String body = "{}";
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httpost = new HttpPost(url);
httpost.setEntity(new UrlEncodedFormEntity(name_value_pair, StandardCharsets.UTF_8));
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
body = EntityUtils.toString(entity);
} finally {
httpclient.getConnectionManager().shutdown();
}
return body;
}
public static String do_get(String url) throws ClientProtocolException, IOException {
String body = "{}";
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
body = EntityUtils.toString(entity);
} finally {
httpclient.getConnectionManager().shutdown();
}
return body;
}

热心网友 时间:2023-10-02 21:16

项目引入别人的API架包即可!

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com