HttpClient请求服务端接口数据Get与Post请求

public static void main(String[] args) {
         //String url = "http://10.3.1.32/proxy_services/MDMConsumerProxyService";
        String url = "http://10.3.1.32/proxy_services/MDMConsumerProxyService";
         try {
            URL restServiceURL = new URL(url);
            HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
            httpConnection.setDoOutput(true);
            httpConnection.setRequestMethod("POST");
            httpConnection.setRequestProperty("Content-Type", "application/json");
            httpConnection.setRequestProperty("loginCode", "gsbf");
            httpConnection.setRequestProperty("loginPassword", "gsbf@2018");
            httpConnection.setRequestProperty("mdmcode", "DWQUERY_V_DISP_JK_GONGSHUIBF_SSJC");
           /* String input = "&name="+ URLEncoder.encode("admin", "UTF-8");
            input+="&password="+ URLEncoder.encode("0000", "UTF-8");*/
            //传递参数
            /*String input = "&loginCode="+ URLEncoder.encode("gsbf", "UTF-8");
            input+="&loginPassword="+ URLEncoder.encode("gsbf@2018", "UTF-8");
            input+="&mdmcode="+ URLEncoder.encode("DWQUERY_V_DISP_JK_GONGSHUIBF_SSJC", "UTF-8");
            input+="&appId="+ URLEncoder.encode("platform_dm.gsbf", "UTF-8");*/
            String input="{\"pageSize\":\"100\"}";
            OutputStream outputStream =httpConnection .getOutputStream();
            outputStream.write(input.getBytes());
            outputStream.flush();
            System.out.println("AAA");
            if (httpConnection.getResponseCode() != 200) {
                throw new RuntimeException(
                "HTTP GET Request Failed with Error code : "
                 + httpConnection.getResponseCode());
                 }
            
            InputStream is = httpConnection.getInputStream();
            byte[] b = new byte[is.available()];
            is.read(b);
            String result  = new String(b,"utf-8");
            System.out.println(result);
            

            
            
            
            
            
            
            
            
            /*InputStream is = httpConnection.getInputStream();
            String resultData = null; // 存储处理结果
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] data = new byte[1024];
            int len = 0;
            try {
                while ((len = is.read(data)) != -1) {
                    byteArrayOutputStream.write(data, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            resultData = new String(byteArrayOutputStream.toByteArray(),"utf-8");
            System.out.println("aa++++"+resultData);*/
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java实现异步批量发送HTTP请求数据服务端可以采用Java的异步框架,如Spring Boot中的异步机制来实现。 具体实现步骤如下: 1. 引入相关依赖:在pom.xml文件中添加Spring Boot的异步依赖,如下所示: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-async</artifactId> </dependency> ``` 2. 创建异步任务:使用@Async注解创建异步任务,如下所示: ``` @Service public class AsyncService { @Async public CompletableFuture<String> sendHttpRequest(String url, String data) throws Exception { // 创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpPost对象 HttpPost httpPost = new HttpPost(url); // 设置请求头 httpPost.setHeader("Content-Type", "application/json"); // 设置请求体 StringEntity entity = new StringEntity(data, "utf-8"); httpPost.setEntity(entity); // 发送请求 CloseableHttpResponse response = httpClient.execute(httpPost); // 处理响应结果 String result = EntityUtils.toString(response.getEntity(), "utf-8"); // 关闭资源 response.close(); httpClient.close(); return CompletableFuture.completedFuture(result); } } ``` 在上述代码中,我们使用@Async注解创建了一个异步任务sendHttpRequest(),该方法用于发送HTTP请求并返回响应结果。 3. 调用异步任务:在需要异步发送HTTP请求的地方,调用异步任务即可,如下所示: ``` @Autowired private AsyncService asyncService; public void sendHttpRequests() throws Exception { List<String> urls = Arrays.asList("http://example.com/api/1", "http://example.com/api/2", "http://example.com/api/3"); List<String> data = Arrays.asList("{\"name\":\"张三\"}", "{\"name\":\"李四\"}", "{\"name\":\"王五\"}"); List<CompletableFuture<String>> futures = new ArrayList<>(); for (int i = 0; i < urls.size(); i++) { CompletableFuture<String> future = asyncService.sendHttpRequest(urls.get(i), data.get(i)); futures.add(future); } CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).join(); List<String> results = futures.stream().map(CompletableFuture::join).collect(Collectors.toList()); // 处理响应结果 // ... } ``` 在上述代码中,我们创建了一个List<CompletableFuture<String>>类型的futures,用于存储异步任务的返回结果。然后,我们循环遍历urls和data,调用异步任务sendHttpRequest()并将返回结果添加到futures列表中。接着,我们使用CompletableFuture.allOf()方法等待所有异步任务执行完毕,然后将所有异步任务的返回结果存储在results列表中,最后对响应结果进行处理。 通过以上步骤,我们就可以实现异步批量发送HTTP请求数据服务端
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值