天天看點

okhttp 通過網關請求服務端傳回資料

okhttp 通過網關請求服務端傳回資料

1、啟動類代碼

package com.tycoon.service;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * Title: ServerConsume1Application
 * Description: 服務啟動類
 *
 * @author tycoon
 * @version 1.0.0
 * @date 2019-02-26 10:10
 */
@EnableDiscoveryClient
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class ServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServerApplication.class, args);
    }
}
      

 2、 application.xml檔案

spring:
  application:
    name: client-request
server:
  port: 7777  #通路項目端口
  servlet:
    context-path: /  #通路項目名稱
  tomcat:
    uri-encoding: UTF-8
logging:
  level:
    root: INFO
    org.springframework.cloud.sleuth: DEBUG
  main:
    allow-bean-definition-overriding: true
  cloud:
    consul:
      discovery:
        instance-id: ${spring.application.name}:${server.port}
        prefer-ip-address: true
        health-check-interval: 10s    #心跳檢查時間間隔
        hostname: ${spring.application.name}
        service-name: ${spring.application.name}
        enabled: true
        health-check-path: /health    #心跳檢查
      host: 127.0.0.1
      port: 8500
      

 3、 測試類代碼

package com.tycoon.service;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Title: ServiceDemoApplicationTests
 * Description: 服務啟動類
 *
 * @author tycoon
 * @version 1.0.0
 * @date 2019-02-26 10:10
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class ServiceDemoApplicationTests {

    @Test
    public void doGetTestOne() {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");//設定日期格式
        String date = df.format(new Date());// new Date()為擷取目前系統時間,也可使用目前時間戳

        System.out.println(date);

        // 獲得Http用戶端(可以了解為:你得先有一個浏覽器;注意:實際上HttpClient與浏覽器是不一樣的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 說明service-provider 為服務提供者,card為服務controller接口,cardId=123456 說的 傳入參數
        String strUrl = "http://localhost:9992/api/service-provider/card?cardId=123456&accessToken=1222";

        // 建立Get請求
        HttpGet httpGet = new HttpGet(strUrl);

       // 響應模型
        CloseableHttpResponse response = null;
        try {
            // 由用戶端執行(發送)Get請求
            response = httpClient.execute(httpGet);
            // 從響應模型中擷取響應實體
            HttpEntity responseEntity = response.getEntity();
            String date1 = df.format(new Date());
            System.out.println("響應狀态為:" + response.getStatusLine()+" ,目前時間:"+date1);

            System.out.println();
            if (responseEntity != null) {
                System.out.println("響應内容為:" + EntityUtils.toString(responseEntity));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 釋放資源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
      

 4、pom.xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <packaging>pom</packaging>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository northeasttycoon -->
    </parent>
    <groupId>com.tycoon</groupId>
    <artifactId>client-request</artifactId>
    <version>1.0.0</version>
    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Finchley.M7</spring-cloud.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-commons</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.7.RELEASE</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-openfeign-core</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.1.15</version>
            </dependency>
            <dependency>
                <groupId>com.squareup.okttp</groupId>
                <artifactId>okhttp</artifactId>
                <version>2.7.5</version>
            </dependency>
            <!--<dependency>-->
                <!--<groupId>com.ning</groupId>-->
                <!--<artifactId>asy-http-client</artifactId>-->
                <!--<version>1.9.31</version>-->
            <!--</dependency>-->
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>
</project>
      

 5、 運作後結果為:

okhttp 通過網關請求服務端傳回資料