Daily Record

This is a non-commercial site, is a record of the life of a technology site

SEARCH


后台间GET/POST通信

作为一名后台人员难免不了要进行和三方进行对接👀️ ,那么就离不开一个后台发送GET或POST请求,通常可以通过多种方法来实现,其中最常见的是使用 HttpURLConnection或第三方库如Apache HttpClient、OkHttp等。下面我将列出使用这些方法的示例以及相关代码🎉️

JAVA 通用

在Java中,有多种库可以帮助你发送HTTP GET和POST请求到另一个后台服务。以下是使用Apache HttpClient和OkHttp的示例,并提供了相应的Maven依赖项。

1. Apache HttpClient

Maven依赖项:

<dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.13</version> <!-- 使用最新版本 -->
  </dependency>

示例代码:

  import org.apache.http.HttpEntity;
  import org.apache.http.client.methods.CloseableHttpResponse;
  import org.apache.http.client.methods.HttpGet;
  import org.apache.http.client.methods.HttpPost;
  import org.apache.http.entity.StringEntity;
  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) throws Exception
      {
          CloseableHttpClient httpClient = HttpClients.createDefault();          // GET请求示例
          HttpGet httpGet = new HttpGet("http://example.com/api/get-endpoint");
          CloseableHttpResponse responseGet = httpClient.execute(httpGet);
          try
         {
              System.out.println(EntityUtils.toString(responseGet.getEntity()));
          }
         finally
         {
              responseGet.close();
          }
          // POST请求示例
          HttpPost httpPost = new HttpPost("http://example.com/api/post-endpoint");
          StringEntity params = new StringEntity("{\"key\":\"value\"}", "UTF-8");
          httpPost.addHeader("content-type", "application/json");
          httpPost.setEntity(params);
          CloseableHttpResponse responsePost = httpClient.execute(httpPost);
          try
          {
              System.out.println(EntityUtils.toString(responsePost.getEntity()));
          }
          finally
         {
              responsePost.close(); 
         }
          httpClient.close();
      }
  }

2. OkHttp

Maven依赖项:

<dependency>
      <groupId>com.squareup.okhttp3</groupId>
      <artifactId>okhttp</artifactId>
      <version>4.9.1</version> <!-- 使用最新版本 -->
  </dependency>

示例代码:

import okhttp3.*;
  import java.io.IOException;
  public class OkHttpExample
  {
      public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
      OkHttpClient client = new OkHttpClient();
      public static void main(String[] args) throws IOException
      {
          OkHttpExample example = new OkHttpExample();          // GET请求示例
          Request requestGet = new Request.Builder().url("http://example.com/api/get-endpoint")                  .build();
          Response responseGet = example.client.newCall(requestGet).execute();
          System.out.println(responseGet.body().string());
          // POST请求示例
          String json = "{\"key\":\"value\"}";
          RequestBody body = RequestBody.create(json, JSON);
          Request requestPost = new Request.Builder().url("http://example.com/api/post-endpoint")                  .post(body).build();
          Response responsePost = example.client.newCall(requestPost).execute();
          System.out.println(responsePost.body().string());
      }
  }

这两个示例分别展示了如何使用Apache HttpClient和OkHttp发送GET和POST请求。记得在实际使用中,替换示例中的URL和请求体为你需要调用的后台服务的实际URL和请求数据。同时,检查并更新Maven依赖项中的版本号,以使用最新的库版本。

SpringBoot

Maven依赖项

首先,你需要在 pom.xml文件中添加Spring Boot Web的依赖项,因为 RestTemplate是Spring Web模块的一部分。

<dependencies>
      <!-- 其他依赖项 -->
      <!-- Spring Boot Web Starter -->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <!-- 如果你需要处理JSON数据,你可能还需要Gson或Jackson的依赖项 -->
      <!-- Gson示例 -->
      <dependency>
          <groupId>com.google.code.gson</groupId>
          <artifactId>gson</artifactId>
      </dependency>
      <!-- 或者Jackson示例 -->
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
      </dependency>
  </dependencies>

发送GET请求

在Spring Boot应用中,你可以通过注入 RestTemplate来发送GET请求。

  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.stereotype.Service;
  import org.springframework.web.client.RestTemplate;
  @Service
  public class ExternalService
  {
      private final RestTemplate restTemplate;
      @Autowired
      public ExternalService(RestTemplate restTemplate)
      {
          this.restTemplate = restTemplate;
      }
      public String getExternalData()
     {
          String url = "http://example.com/api/get-endpoint";
          return restTemplate.getForObject(url, String.class);
      }
  }

发送POST请求

对于POST请求,你可以使用 postForObjectpostForEntity方法,取决于你是否需要完整的响应实体。

import org.springframework.http.HttpEntity;
  import org.springframework.http.HttpHeaders;
  import org.springframework.http.MediaType;
  import org.springframework.stereotype.Service;
  import org.springframework.web.client.RestTemplate;
  @Service
  public class ExternalService
  {
      private final RestTemplate restTemplate;
      @Autowired
      public ExternalService(RestTemplate restTemplate)
      {
          this.restTemplate = restTemplate;
      }
      public String postExternalData(Object requestBody)
     {
          String url = "http://example.com/api/post-endpoint";
          HttpHeaders headers = new HttpHeaders();
          headers.setContentType(MediaType.APPLICATION_JSON);
          HttpEntity<Object> entity = new HttpEntity<>(requestBody, headers);
          return restTemplate.postForObject(url, entity, String.class);
      }
  }

配置RestTemplate(可选)

在Spring Boot应用中,RestTemplate通常是通过自动配置提供的。但是,如果你需要自定义配置(例如,添加拦截器、设置超时等),你可以创建一个 RestTemplate的Bean。

import org.springframework.context.annotation.Bean;
  import org.springframework.context.annotation.Configuration;
  import org.springframework.web.client.RestTemplate;
  @Configuration
  public class RestTemplateConfig
  {
      @Bean
      public RestTemplate restTemplate()
      {
          return new RestTemplate(); // 可以添加自定义配置
      }
  }

注意:从Spring 5开始,推荐使用 WebClient作为非阻塞的替代方案,特别是在响应式应用中。但是,对于简单的同步请求,RestTemplate仍然是一个很好的选择。

至此已经完事了,又在大神面前丢脸了😄 ,无所谓了希望能帮助一部朋友就行

最近的文章

android.support.test.InstrumentationRegistry 这个错误信息表示你的代码中尝试导入了 android.support.test.InstrumentationRegistry,但是这个类在你的项目中找不到。这个问题通常是因为Android Support库已…

继续阅读
更早的文章

解决Android项目中Java反射访问限制问题 在Android开发过程中,有时我们需要导入并运行一些新的项目。然而,在这个过程中可能会遇到各种挑战,其中之一就是Java的模块系统引入的访问限制。当尝试通过反射访问Java核心类库(如 java.io.File中的私有字段)时,可能会遇到类似以下的…

继续阅读