HttpClient和ServerSocket通信实例代码

//HttpClent客户端代码

package
jvm; import java.io.IOException; import java.net.URISyntaxException; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.ParseException; import org.apache.hc.core5.http.io.entity.EntityUtils; public class HttpClientDemoTest01 { public static void main(String args[]){ // 创建一个HttpClient CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; try { //创建HttpGet HttpGet httpGet = new HttpGet("http://localhost:8801/"); System.out.println("execute request:"+httpGet.getUri()); //执行get请求 response = httpClient.execute(httpGet); //获取响应实体 HttpEntity entity = response.getEntity(); //打印响应状态 if(entity!=null){ System.out.println(entity.getContentLength()); System.out.println(EntityUtils.toString(entity)); } } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { response.close(); httpClient.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
//ServerSocket服务端代码

package
jvm; import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class HttpServer01 { public static void main(String args[]) throws IOException{ ServerSocket serverSocket = new ServerSocket(8801); while(true){ Socket socket = serverSocket.accept(); service(socket); } } private static void service(Socket socket) { try { PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true); printWriter.println("HTTP/1.1 200 OK"); printWriter.println("Content-Type:text/html;charset=utf-8"); String body = "Hello nio1"; printWriter.println("Conttent-Length:"+body.getBytes().length); printWriter.println(); printWriter.write(body); printWriter.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } } }

HttpClient和ServerSocket通信实例代码

 

 上图所示是java项目目录结构,以及需要导入的jar包  首先启动ServerSocket服务,然后再启动HttpClient程序,结果如下所示。

HttpClient和ServerSocket通信实例代码

 

下面我们来了解一下HttpClient 和 ServerSocket.

HttpClient:

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。

下载地址: http://hc.apache.org/downloads.cgi

HttpClient的主要功能:

  • 实现了所有 HTTP 的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)
  • 支持 HTTPS 协议
  • 支持代理服务器(Nginx等)等
  • 支持自动(跳转)转向

 

HttpClient和ServerSocket通信实例代码

上一篇:ESXI6.0开启网页控制UI


下一篇:Linux Netfilter框架分析