使用HttpGet,closeableHttpClient,HttpClients,CloseableHttpResponse实现本地访问web服务器

一、架包

httpclient-4.4.1.jar  httpcore-4.4.1.jar   httpmime-4.2.jar

二、例子

String url="http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

HttpGet httpGet = new HttpGet(url);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = httpclient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            httpGet.abort();
            throw new RuntimeException("HttpClient,error status code :" + statusCode);
        }
        HttpEntity entity = response.getEntity();
        String result = null;
        if (entity != null) {
            result = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
            response.close();
            System.out.println(result);
        }

 

三、使用多线程以及CountDownLatch实现共同访问

public class Test {
public static void main(String[] args) {
    CountDownLatch latch=new CountDownLatch(1);
    String url="http://test.meyki.net:9080/apidev/v3/goods/goodsList/eyJwYWdlU2l6ZSI6IjIwIiwib3MiOiJpb3MiLCJzaG9wSWQiOiI1MTU2MjNmNGVlOGU0OGIxYmU3MmY2MGFiOTcxZTExOSIsInVzZXJJZCI6IjIyNTg0MDVmYTU5ODRlOTViNWI2NTI4ZTM3YmExODBjIiwicGFnZU5vIjoiMSIsImlzU2hlbHZlcyI6IjEiLCJ2Y29kZSI6IjE0MCIsInRhZyI6IjEifQ==";
    for(int i=0;i<=15;i++){
        Thread thread=new Thread(new Mythread(latch,url));
        thread.start();
    }
    latch.countDown();
}
}
 1 package com.meyki.common;
 2 
 3 import java.io.IOException;
 4 import java.util.concurrent.CountDownLatch;
 5 
 6 import org.apache.http.HttpEntity;
 7 import org.apache.http.ParseException;
 8 import org.apache.http.client.methods.CloseableHttpResponse;
 9 import org.apache.http.client.methods.HttpGet;
10 import org.apache.http.impl.client.CloseableHttpClient;
11 import org.apache.http.impl.client.HttpClients;
12 import org.apache.http.util.EntityUtils;
13 
14 import okhttp3.OkHttpClient;
15 import okhttp3.Request;
16 import okhttp3.Response;
17 
18 public class Mythread  implements Runnable{
19     private final CountDownLatch startSignal;
20     private  String url;
21     public Mythread(CountDownLatch  startSignal,String url){
22         super();
23         this.startSignal=startSignal;
24         this.url=url;
25     }
26     @Override
27     public void run() {
28         try {
29             startSignal.await();
30         } catch (InterruptedException e) {
31             // TODO Auto-generated catch block
32             e.printStackTrace();
33         }
34         try {
35             dowork();
36         } catch (ParseException e) {
37             // TODO Auto-generated catch block
38             e.printStackTrace();
39         } catch (IOException e) {
40             // TODO Auto-generated catch block
41             e.printStackTrace();
42         }
43     }
44     private void dowork() throws ParseException, IOException {
45         
46         //使用HttpGet,closeableHttpClient,HttpClients,CloseableHttpResponse在本地访问
47         HttpGet httpGet = new HttpGet(url);
48         CloseableHttpClient httpclient = HttpClients.createDefault();
49         CloseableHttpResponse response = httpclient.execute(httpGet);
50         int statusCode = response.getStatusLine().getStatusCode();
51         if (statusCode != 200) {
52             httpGet.abort();
53             throw new RuntimeException("HttpClient,error status code :" + statusCode);
54         }
55         HttpEntity entity = response.getEntity();
56         String result = null;
57         if (entity != null) {
58             result = EntityUtils.toString(entity, "utf-8");
59             EntityUtils.consume(entity);
60             response.close();
61             System.out.println(result);
62         }
63         //使用OkhttpClient
64         /*OkHttpClient   httpClient=new OkHttpClient();
65         Request request=new Request.Builder()
66                         .url(url)
67                         .build();
68         //得到response对象
69         Response response=httpClient.newCall(request).execute();
70         if(response.isSuccessful()){
71             String result=response.body().string();
72             System.out.println(response.code());
73             System.out.println(response.message());
74             System.out.println(result);
75         }*/
76     }
77         
78 }

 

转载于:https://www.cnblogs.com/wwwcf1982603555/p/9088695.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python可以使用多种方式实现一个能够处理GET请求的Web服务器,其中最常见的方式是使用Python中的内置模块`http.server`。 首先,我们需要导入`http.server`模块。然后,创建一个类继承自`http.server.BaseHTTPRequestHandler`,该类将用于处理来自客户端的HTTP请求。 在这个类中,我们需要重写`do_GET`方法,用于处理GET请求。在这个方法中,我们可以根据请求路径的不同返回不同的内容或执行不同的操作。 下面是一个简单的示例代码: ```python import http.server class MyHandler(http.server.BaseHTTPRequestHandler): def do_GET(self): if self.path == '/': # 如果请求路径为根目录 self.send_response(200) # 设置响应状态码为200 self.send_header('Content-type', 'text/html') # 设置响应头 self.end_headers() self.wfile.write(b'Hello, World!') # 返回响应内容 elif self.path == '/about': # 如果请求路径为/about self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(b'About page') else: # 其他情况返回404 Not Found错误 self.send_response(404) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(b'404 Not Found') # 创建服务器实例,并指定请求处理类为MyHandler server = http.server.HTTPServer(('localhost', 8080), MyHandler) # 开启服务器,一直监听客户端请求 server.serve_forever() ``` 上述代码实现了一个能够处理GET请求的简单Web服务器。通过访问`http://localhost:8080/`将返回`Hello, World!`,访问`http://localhost:8080/about`将返回`About page`,访问其他路径将返回`404 Not Found`错误。 ### 回答2: Python实现一个用于处理GET请求的Web服务器可以使用Python的内置模块http.server。下面是一个简单的示例代码: ```python from http.server import BaseHTTPRequestHandler, HTTPServer class RequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() # 处理GET请求 if self.path == '/': self.wfile.write(b'Hello, World!') elif self.path == '/about': self.wfile.write(b'About page') else: self.wfile.write(b'404 Not Found') def run_server(): address = ('', 8000) # 指定服务器地址和端口号 server = HTTPServer(address, RequestHandler) print('Starting server on http://localhost:8000 ...') server.serve_forever() if __name__ == '__main__': run_server() ``` 以上代码定义了一个RequestHandler类,继承自BaseHTTPRequestHandler。实现了一个do_GET方法用于处理GET请求。根据不同的路径(self.path),返回相应的内容。在run_server函数中创建HTTPServer实例,并启动Web服务器。在浏览器中打开http://localhost:8000 可以看到"Hello, World!"的响应。访问http://localhost:8000/about 可以看到"About page"的响应。如果访问其他路由则返回"404 Not Found"。这是一个非常简单的示例,实际的Web服务器通常需要处理更多的逻辑和数据。 ### 回答3: 在Python中,我们可以使用内置的`http.server`模块来实现一个基本的Web服务器,用于处理GET请求。以下是一个简单的示例: ``` import http.server import socketserver PORT = 8000 Handler = http.server.SimpleHTTPRequestHandler with socketserver.TCPServer(("", PORT), Handler) as httpd: print("服务器正在运行,访问 http://localhost:8000/ 查看结果") httpd.serve_forever() ``` 上述代码中,我们使用`socketserver.TCPServer`创建了一个TCP服务器,并将其绑定到本地的8000端口上。`Handler`参数指定了服务器内部使用的请求处理程序,我们使用`http.server.SimpleHTTPRequestHandler`作为处理GET请求的默认处理程序。 最后,我们通过调用`serve_forever()`方法启动了服务器,并使用`print`语句输出了访问服务器的地址。这样,我们就实现了一个简单的Web服务器,可以通过访问http://localhost:8000/来查看结果。 需要注意的是,上述代码只是一个简单的示例,它提供了一个基本的文件服务器,用于处理GET请求并将请求的文件发送给客户端。如果想要实现更复杂的Web应用程序,可能需要使用更强大的框架,例如Flask或Django。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值