学到了新知识就分享一下,追逐我那去往远方的朋友。
我们在代码中有时候需要调用网络上的接口,如天气预报等接口,不可能我们自己再去采集天气信息存在库里哈哈哈哈哈,这时候就要写方法类调用接口,再在需要的地方调用这个方法。
方法有若干种,这里先只说用Apache HttpClient实现的:
1,首先需要在你的pom.xml文件中添加Apache HttpClient的依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
以下几种方法分为:get和post,传参和不传参,返回的值为字符串还是json
2,不用传参数的形式,返回字符串结果:
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class ApacheHttpClientExample {
public static String getDataFromApi(String apiUrl) {
String result = "";
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet request = new HttpGet(apiUrl);
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
result = EntityUtils.toString(response.getEntity());
} else {
System.out.println("GET request failed with status code: " + statusCode);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
String apiUrl = "https://api.example.com/data";
String result = getDataFromApi(apiUrl);
System.out.println(result);
}
}
3,get需要传参数的形式,参数数量自己调整:
注意导入这两个包,将浏览器拿来的参数进行转换
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class ApacheHttpClientExample {
public static String getDataFromApi(String baseUrl, String param1, String param2) {
String result = "";
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
String encodedParam1 = URLEncoder.encode(param1, StandardCharsets.UTF_8.toString());
String encodedParam2 = URLEncoder.encode(param2, StandardCharsets.UTF_8.toString());
String apiUrl = baseUrl + "?param1=" + encodedParam1 + "¶m2=" + encodedParam2;
HttpGet request = new HttpGet(apiUrl);
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
result = EntityUtils.toString(response.getEntity());
} else {
System.out.println("GET request failed with status code: " + statusCode);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
String baseUrl = "https://api.example.com/data";
String result = getDataFromApi(baseUrl, "value1", "value2");
System.out.println(result);
}
}
如果网络接口返回的是json形式内容,可以选择以字符串返回后处理:
//调用天气接口的工具类
String result = ApacheHttpClient.getWeatherFromApi(address, locationId,key);
//格式转换
JSONObject bodyJson = JSONObject.parseObject(result);
4,get需要传参数的方式,返回json:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class ApacheHttpClientExample {
// 方法用于从 API 获取数据
public static JsonNode getDataFromApi(String baseUrl, String param1, String param2) {
JsonNode jsonResult = null;
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
String encodedParam1 = URLEncoder.encode(param1, StandardCharsets.UTF_8.toString());
String encodedParam2 = URLEncoder.encode(param2, StandardCharsets.UTF_8.toString());
String apiUrl = baseUrl + "?param1=" + encodedParam1 + "¶m2=" + encodedParam2;
HttpGet request = new HttpGet(apiUrl);
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
String result = EntityUtils.toString(response.getEntity());
ObjectMapper mapper = new ObjectMapper();
jsonResult = mapper.readTree(result);
} else {
System.out.println("GET request failed with status code: " + statusCode);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return jsonResult;
}
public static void main(String[] args) {
String baseUrl = "https://api.example.com/data";
JsonNode result = getDataFromApi(baseUrl, "value1", "value2");
System.out.println(result.toPrettyString());
}
}
5,post传参数的方式,返回字符串:
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class ApacheHttpClientExample {
public static String postDataToApi(String apiUrl, String param1, String param2) {
String result = "";
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost post = new HttpPost(apiUrl);
post.setHeader("Content-Type", "application/json");
// 构建JSON格式的请求体
String json = "{\"param1\":\"" + param1 + "\",\"param2\":\"" + param2 + "\"}";
StringEntity entity = new StringEntity(json);
post.setEntity(entity);
try (CloseableHttpResponse response = httpClient.execute(post)) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
result = EntityUtils.toString(response.getEntity());
} else {
System.out.println("POST request failed with status code: " + statusCode);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
String apiUrl = "https://api.example.com/data";
String result = postDataToApi(apiUrl, "value1", "value2");
System.out.println(result);
}
}
6,post传参数的方式,返回json:
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class ApacheHttpClientExample {
public static JsonNode postDataToApi(String apiUrl, String param1, String param2) {
JsonNode jsonResult = null;
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost post = new HttpPost(apiUrl);
post.setHeader("Content-Type", "application/json");
// 构建JSON格式的请求体
String json = "{\"param1\":\"" + param1 + "\",\"param2\":\"" + param2 + "\"}";
StringEntity entity = new StringEntity(json);
post.setEntity(entity);
try (CloseableHttpResponse response = httpClient.execute(post)) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
String result = EntityUtils.toString(response.getEntity());
ObjectMapper mapper = new ObjectMapper();
jsonResult = mapper.readTree(result);
} else {
System.out.println("POST request failed with status code: " + statusCode);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
String apiUrl = "https://api.example.com/data";
JsonNode result = postDataToApi(apiUrl, "value1", "value2");
System.out.println(result);
}
}