Java基於HttpClient實現RPC的示例

1 HttpClient簡介

在JDK中java.net包下提供瞭用戶HTTP訪問的基本功能,但是它缺少靈活性或許多應用所需要的功能。

​ HttpClient起初是Apache Jakarta Common 的子項目。用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,並且它支持 HTTP 協議最新的版本。2007年成為頂級項目。

​ 通俗解釋:HttpClient可以實現使用Java代碼完成標準HTTP請求及響應。

2 代碼實現

2.1 服務端

新建項目HttpClientServer

2.1.1 新建控制器

com.mrshun.controller.DemoController

@Controller
public class DemoController {
    @RequestMapping("/demo")
    @ResponseBody
    public String demo(String param){
        return "demo"+param;
    }
}

2.1.2 新建啟動器

新建啟動器

com.mrshun.HttpClientServerApplication

@SpringBootApplication
public class HttpClientServerApplication {
    public static void main(String[] args) {
    SpringApplication.run(HttpClientServerApplication.class,args);
    }
}

2.2 客戶端

新建HttpClientDemo項目

2.2.1 添加依賴

<dependencies>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.10</version>
    </dependency>
</dependencies>

2.2.2 新建類

新建com.mrshun.HttpClientDemo,編寫主方法。

2.2.2.1 使用GET方法訪問

public static void main(String[] args) {
    try {
     //創建http工具(理解成:瀏覽器) 發起請求,解析響應
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //請求路徑
        URIBuilder uriBuilder = new URIBuilder("http://localhost:8080/demo");
        uriBuilder.addParameter("param", "get123");
        //創建HttpGet請求對象
        HttpGet get = new HttpGet(uriBuilder.build());
        //創建響應對象
        CloseableHttpResponse response = httpClient.execute(get);
        //由於響應體是字符串,因此把HttpEntity類型轉換為字符串類型,並設置字符編碼
        String result = EntityUtils.toString(response.getEntity(), "utf-8");
        //輸出結果
        System.out.println(result);
        //釋放資源
        response.close();
        httpClient.close();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

2.2.2.2 使用POST方式訪問

public class HttpClientDemo {
    public static void main(String[] args) {
        try {
         //創建http工具(理解成:瀏覽器) 發起請求,解析響應
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //創建HttpPOST請求對象
            HttpPost post = new HttpPost("http://localhost:8080/demo");
            //所有請求參數
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("param","123"));
            //創建HttpEntity接口的文本實現類的對象,放入參數並設置編碼
            HttpEntity httpEntity = new UrlEncodedFormEntity(params,"utf-8");
            //放入到HttpPost對象中
            post.setEntity(httpEntity);            
            //創建響應對象
            CloseableHttpResponse response = httpClient.execute(post);
            //由於響應體是字符串,因此把HttpEntity類型轉換為字符串類型
            String result = EntityUtils.toString(response.getEntity());
            //輸出結果
            System.out.println(result);
            //釋放資源
            response.close();
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. Jackson用法

3.1 把對象轉換為json字符串

ObjectMapper objectMapper = new ObjectMapper();
People peo = new People();
objectMapper.writeValueAsString(peo);

3.2 把json字符串轉換為對象

ObjectMapper objectMapper = new ObjectMapper();
People peo = objectMapper.readValue(content, People.class);

3.3 把json字符串轉換為List集合

ObjectMapper objectMapper = new ObjectMapper();
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, People.class);
List<People> list = objectMapper.readValue(content, javaType);

4 HttpClient請求包含JSON

4.1 java代碼實現

public class HttpClientDemo {
    public static void main(String[] args) {
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost post = new HttpPost("http://localhost:8080/demo");
            HttpEntity httpEntity= null;
String json = "{}";
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            post.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(post);
            String result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
            response.close();
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

5 控制器接口參數

@RequestBody把請求體中流數據轉換為指定的對象。多用在請求參數是json數據且請求的Content-Type=”application/json”

@RequestMapping("/demo4")
@ResponseBody
public String demo4(@RequestBody List<People> list) {
    System.out.println(list);
    return list.toString();
}

6 Ajax發送json參數寫法

var json = '[{"id":123,"name":"mrshun"},{"id":123,"name":"zhangyongshun"}]';
 $.ajax({
     url:'/demo5',
     type:'post',
     success:function(data){
         alert(data);
         for(var i = 0 ;i<data.length;i++){

             alert(data[i].id +"  "+data[i].name);
         }
     },
     contentType:'application/json',//請求體中內容類型
     dataType:'json',//響應內容類型。
     data:json
 });

7 跨域

  • 跨域:協議、ip、端口中隻要有一個不同就是跨域請求。
  • 同源策略:瀏覽器默認隻允許ajax訪問同源(協議、ip、端口都相同)內容。

解決同源策略:

​ 在控制器接口上添加@CrossOrigin。表示允許跨域。本質在響應頭中添加Access-Control-Allow-Origin: *

var json = '[{"id":123,"name":"mrshun"},{"id":456,"name":"zhangyongshun"}]';
 $.ajax({
     url:'/demo5',
     type:'post',
     success:function(data){
         alert(data);
         for(var i = 0 ;i<data.length;i++){

             alert(data[i].id +"  "+data[i].name);
         }
     },
     contentType:'application/json',//請求體中內容類型
     dataType:'json',//響應內容類型。
     data:json
 });

到此這篇關於Java基於HttpClient實現RPC的示例的文章就介紹到這瞭,更多相關Java HttpClient實現RPC內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: