Java 快递物流查询
引言
随着电子商务的兴起和物流行业的发展,快递物流查询成为了人们日常生活中的重要需求。通过快递物流查询服务,人们可以方便地了解自己购买的商品的物流状态,从而更好地安排自己的时间和行程。本文将介绍如何使用 Java 编程语言开发一个简单的快递物流查询系统,并提供代码示例。
快递物流查询系统的工作原理
快递物流查询系统的工作原理如下:
- 用户输入快递单号和物流公司名称。
- 系统根据用户输入的物流公司名称和快递单号,调用相应的物流查询接口。
- 物流查询接口向物流公司的服务器发送请求,获取物流信息。
- 物流公司的服务器返回物流信息给物流查询接口。
- 物流查询接口将物流信息返回给系统。
- 系统将物流信息展示给用户。
Java 中的网络请求
在 Java 中,我们可以使用一些库来发送网络请求并获取响应。其中,比较常用的库有 Apache HttpClient 和 OkHttp。下面是使用 Apache HttpClient 发送 GET 请求的示例代码:
import org.apache.http.HttpEntity;
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 HttpClientExample {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("
try {
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity);
System.out.println(responseBody);
} catch (Exception e) {
e.printStackTrace();
}
}
}
在这个例子中,我们创建了一个 CloseableHttpClient
对象,并使用 HttpGet
对象来表示一个 GET 请求。然后,我们使用 httpClient.execute(httpGet)
来发送请求并获取响应,最后通过 EntityUtils.toString(entity)
将响应实体转换成字符串。
快递物流查询系统的实现
为了方便演示,我们假设有一个物流公司的快递物流查询接口,可以根据快递单号返回物流信息。我们的目标是通过开发一个简单的 Java 程序来调用这个接口并展示物流信息给用户。
首先,我们需要定义一个 ExpressApi
类来封装物流查询接口:
import org.apache.http.HttpEntity;
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 ExpressApi {
private String baseUrl;
public ExpressApi(String baseUrl) {
this.baseUrl = baseUrl;
}
public String getExpressInfo(String trackingNumber) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(baseUrl + "?tracking_number=" + trackingNumber);
try {
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
在这个类中,我们通过构造函数传入基本的 API 地址,然后定义了一个 getExpressInfo
方法,该方法接收一个快递单号作为参数,并返回物流信息。
接下来,我们可以编写一个简单的控制台程序来使用 ExpressApi
类:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入快递单号:");
String trackingNumber = scanner.nextLine();
System.out.print("请输入物流公司名称:");
String expressCompany = scanner.nextLine();
ExpressApi expressApi = new ExpressApi("
String expressInfo = expressApi.getExpressInfo(trackingNumber);
System.out.println("物流信息:" + expressInfo);
}
}
在这个程序中,我们使用 Scanner
类从用户输入中获取快递单号和物流公司名称,并调用 `Express