httpcore/httpclient简单实例
-
项目摘要:
- 项目具体实施:
- httpcore实例
- 新建一个maven项目,引入如下jar包:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.9</version>
</dependency>
<!-- <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore-nio</artifactId>
<version>4.4.4</version>
</dependency> -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
- 进入http://hc.apache.org/httpcomponents-core-4.4.x/examples.html网站,选择Synchronous HTTP file server ,将其代码复制进自己新建的一个类,比如该项目里的Application.java,修改代码如下:
package com;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.http.ExceptionLogger;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.bootstrap.HttpServer;
import org.apache.http.impl.bootstrap.ServerBootstrap;
import com.handle.HttpAdminHandler;
import com.handle.HttpUserHandler;
/**
*
* 实例:http://hc.apache.org/httpcomponents-core-4.4.x/examples.html
*/
public class Application {
public static void main(final String[] args) throws Exception {
try {
int port = 8080;
SocketConfig socketConfig = SocketConfig.custom()
.setSoTimeout(15000)
.setTcpNoDelay(true)
.build();
final HttpServer server = ServerBootstrap.bootstrap()
.setListenerPort(port) //端口号
.setServerInfo("Test/1.1") //
.setSocketConfig(socketConfig)
.setExceptionLogger(ExceptionLogger.STD_ERR)
// 注册httpHandler
//.registerHandler("/user*", new HttpUserHandler())
//.registerHandler("/admin*", new HttpAdminHandler())
.create();
server.start();
System.out.println("启动成功!");
server.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
server.shutdown(5, TimeUnit.SECONDS);
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
- 上述代码实现了自己的两个业务类,分别是
//.registerHandler("/user*", new HttpUserHandler())
//.registerHandler("/admin*", new HttpAdminHandler())
由于这两个业务类涉及到一个实体类(Admin中未实现其业务)和一个业务类,该项目数据为模拟数据,并没有从数据库保存数据。
其中,实体类User.java为:
package com.entity;
import java.io.Serializable;
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String name;
private int age;
private String job;
public User() {
super();
}
public User(int id, String name, int age, String job) {
super();
this.id = id;
this.name = name;
this.age = age;
this.job = job;
}
/*********get / set************/
}
业务类UserService.java为:
- 接口类:
package com.service;
import java.util.List;
import com.entity.User;
public interface IUserSevice {
List<User> getAllUser();
User getUserById(int id);
void deleteUserById(int id);
void addUser(User user);
}
- 实现类
package com.service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.entity.User;
public class UserService implements IUserSevice{
private List<User> users=new ArrayList<User>();
public UserService() {
users.add(new User(1, "Tom", 12, "java开发"));
users.add(new User(2, "Jack", 12, "java测试"));
users.add(new User(3, "David", 12, "Python开发"));
users.add(new User(4, "Mary", 12, "前端开发"));
users.add(new User(5, "Smith", 12, "java大数据开发"));
}
public List<User> getAllUser() {
return users;
}
public User getUserById(int id) {
for (User user : users) {
if (user.getId()==id) {
return user;
}
}
return null;
}
public void deleteUserById(int id) {
Iterator<User> it=users.iterator();
while (it.hasNext()) {
User user = (User) it.next();
if (user.getId()==id) {
it.remove();
}
}
}
public void addUser(User user) {
user.getId();
users.add(user);
}
}
- HttpUserHandler注册类:
package com.handle;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import com.entity.User;
import com.service.UserService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class HttpUserHandler implements HttpRequestHandler {
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
throw new MethodNotSupportedException(method + "方法不被支持");
}
String target = request.getRequestLine().getUri();
System.out.println("前端发来的请求:" + target);
UserService userService=new UserService();
if (target.equals("/user")&&method.equals("GET")) {
List<User> users = userService.getAllUser();
JSONArray json = JSONArray.fromObject(users);
StringEntity entity = new StringEntity(json.toString(), ContentType.create("application/json", "UTF-8"));
response.setEntity(entity);
}else if(target.equals("/user/1")&&method.equals("GET")){
User user = userService.getUserById(1);
JSONObject json = JSONObject.fromObject(user);
StringEntity entity = new StringEntity(json.toString(), ContentType.create("application/json", "UTF-8"));
response.setEntity(entity);
}
else {
response.setEntity(new StringEntity("没有这个服务", ContentType.create("text/html", "UTF-8")));
}
}
}
- HttpAdminHandler注册类
package com.handle;
/****import****/
public class HttpAdminHandler implements HttpRequestHandler {
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
throws HttpException, IOException {
System.out.println("admin:"+request.getRequestLine().getUri());
StringEntity entity = new StringEntity("管理员模块", ContentType.create("application/json", "UTF-8"));
response.setEntity(entity);
}
}
运行Application.java类,浏览器输入localhost:8080/user,则输出所有用户信息。上述代码其他模块还未实现,可以作为练习而完成。
- httpclient实例
- 新建一个客户端项目,引入相关jar包:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
- 新建HttpClientGetDemo.java类,由于官网没有权限进入示例代码,所以参考网络资源后,编写如下代码
package com.request.demo;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
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;
/**
* 参考: https://www.cnblogs.com/yoci/p/10232171.html
*/
public class HttpClientGetDemo {
/**
* httpClient Get请求
*/
public static void main(String[] args) throws IOException {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
// 第一步 配置 get 请求 url
HttpGet httpget = new HttpGet("http://localhost:8080/user");
// 第二步 创建一个自定义的 response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws IOException {
int status = response.getStatusLine().getStatusCode();
System.out.println("status:" + status);
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
};
// 第三步 执行请求
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println(responseBody);
}
}
}
启动服务端,然后运行客户端,输出所有用户信息。这里有一点,服务端会出现客户断已断开的错误,暂时还没有得到解决。该示例同样很多业务是没有实现的,可以作为练习添加其他模块。
本文相关资源(文档和代码同本文一致,无需下载):https://download.****.net/download/qq_25337221/12445221
- 参考链接:
1. apache httpcore:
http://hc.apache.org/httpcomponents-core-4.4.x/examples.html
2. httpclient实例: https://www.cnblogs.com/yoci/p/10232171.html
本内容由安康学院“雨季”原创。