>  기사  >  Java  >  Java를 사용하여 http 요청을 구현하는 방법

Java를 사용하여 http 요청을 구현하는 방법

WBOY
WBOY앞으로
2023-06-02 16:57:471053검색

1. 개요

실제 개발 과정에서는 상대방이 제공한 인터페이스를 호출하거나 우리가 작성한 인터페이스가 적합한지 테스트해야 하는 경우가 많습니다. 많은 프로젝트가 자체 프로젝트의 인터페이스 사양을 캡슐화하고 지정하므로 대부분은 상대방이 제공하는 인터페이스나 타사 인터페이스(문자 메시지, 날씨 등)를 호출해야 합니다.

Java 프로젝트에서 타사 인터페이스를 호출하는 방법은 다음과 같습니다.

1. JDK 네트워크 클래스 Java.net.HttpURLConnection을 통해

2. Apache로 캡슐화된 HttpClient를 통해; CloseableHttpClient;

4. SpringBoot-RestTemplate을 통해

2. Java가 타사 http 인터페이스를 호출하는 방법

2.1 JDK 네트워크 클래스 Java.net.HttpURLConnection

을 통해 get 요청 및 게시 요청은 모두 하나의 방법으로 배치됩니다.

구현 프로세스:

GET:

1. 원격 연결 만들기

2. 연결 방법 설정(get, post, put...)

3 연결 시간 초과 설정

4. 읽기 시간

5. 요청 시작

7. 연결 종료

POST:

1. 연결 방법 설정(get, post, put) ...)

3 , 연결 시간 초과 설정

4. 응답 읽기 시간 설정

5. 원격 서버에 데이터 전송/쓰기 시 true(setDoOutput)로 설정되어야 합니다. 6. 원격 서비스에서 데이터 읽기, 설정은 true입니다. 이 매개변수는 선택사항입니다(setDoInput)

7. 수신 매개변수의 형식 설정: (setRequestProperty)

8. 인증 정보 설정: 인증: (setRequestProperty)

9. 매개변수 설정

10. 요청 시작

12. 연결을 닫습니다.

코드로 직접 이동:

package com.riemann.springbootdemo.util.common.httpConnectionUtil;
 
import org.springframework.lang.Nullable;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
 
/**
 * @author riemann
 * @date 2019/05/24 23:42
 */
public class HttpURLConnectionUtil {
 
    /**
     * Http get请求
     * @param httpUrl 连接
     * @return 响应数据
     */
    public static String doGet(String httpUrl){
        //链接
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuffer result = new StringBuffer();
        try {
            //创建连接
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            //设置连接超时时间
            connection.setReadTimeout(15000);
            //开始连接
            connection.connect();
            //获取响应数据
            if (connection.getResponseCode() == 200) {
                //获取返回的数据
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭远程连接
            connection.disconnect();
        }
        return result.toString();
    }
 
    /**
     * Http post请求
     * @param httpUrl 连接
     * @param param 参数
     * @return
     */
    public static String doPost(String httpUrl, @Nullable String param) {
        StringBuffer result = new StringBuffer();
        //连接
        HttpURLConnection connection = null;
        OutputStream os = null;
        InputStream is = null;
        BufferedReader br = null;
        try {
            //创建连接对象
            URL url = new URL(httpUrl);
            //创建连接
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方法
            connection.setRequestMethod("POST");
            //设置连接超时时间
            connection.setConnectTimeout(15000);
            //设置读取超时时间
            connection.setReadTimeout(15000);
            //DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
            //设置是否可读取
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
 
            //拼装参数
            if (null != param && param.equals("")) {
                //设置参数
                os = connection.getOutputStream();
                //拼装参数
                os.write(param.getBytes("UTF-8"));
            }
            //设置权限
            //设置请求头等
            //开启连接
            //connection.connect();
            //读取响应
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "GBK"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                        result.append("\r\n");
                    }
                }
            }
 
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭连接
            connection.disconnect();
        }
        return result.toString();
    }
 
    public static void main(String[] args) {
        String message = doPost("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "");
        System.out.println(message);
    }
}

실행 결과:

2.2 요청 방법 단계 Apache common

httpClient로 캡슐화된 HttpClient:

1. HttpClient 개체를 생성하고 해당 매개변수를 설정합니다.

2. GetMethod 개체 또는 PostMethod를 생성하고 HttpClient에서 생성된 개체를 사용합니다. GetMethod에 의해 생성된 Get 메소드를 실행합니다. 4. 응답 상태 코드를 처리합니다.

Java를 사용하여 http 요청을 구현하는 방법5. 응답이 정상이면 연결을 해제합니다.

다음 jar 패키지 가져오기:

<!--HttpClient-->
<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>
 
<!--fastjson-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.32</version>
</dependency>

코드는 다음과 같습니다.

package com.riemann.springbootdemo.util.common.httpConnectionUtil;
 
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
 
import java.io.IOException;
 
/**
 * @author riemann
 * @date 2019/05/25 0:58
 */
public class HttpClientUtil {
    /**
     * httpClient的get请求方式
     * 使用GetMethod来访问一个URL对应的网页实现步骤:
     * 1.生成一个HttpClient对象并设置相应的参数;
     * 2.生成一个GetMethod对象并设置响应的参数;
     * 3.用HttpClient生成的对象来执行GetMethod生成的Get方法;
     * 4.处理响应状态码;
     * 5.若响应正常,处理HTTP响应内容;
     * 6.释放连接。
     * @param url
     * @param charset
     * @return
     */
    public static String doGet(String url, String charset) {
        //1.生成HttpClient对象并设置参数
        HttpClient httpClient = new HttpClient();
        //设置Http连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        //2.生成GetMethod对象并设置参数
        GetMethod getMethod = new GetMethod(url);
        //设置get请求超时为5秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        //设置请求重试处理,用的是默认的重试处理:请求三次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        String response = "";
        //3.执行HTTP GET 请求
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            //4.判断访问的状态码
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("请求出错:" + getMethod.getStatusLine());
            }
            //5.处理HTTP响应内容
            //HTTP响应头部信息,这里简单打印
            Header[] headers = getMethod.getResponseHeaders();
            for(Header h : headers) {
                System.out.println(h.getName() + "---------------" + h.getValue());
            }
            //读取HTTP响应内容,这里简单打印网页内容
            //读取为字节数组
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);
            System.out.println("-----------response:" + response);
            //读取为InputStream,在网页内容数据量大时候推荐使用
            //InputStream response = getMethod.getResponseBodyAsStream();
        } catch (HttpException e) {
            //发生致命的异常,可能是协议不对或者返回的内容有问题
            System.out.println("请检查输入的URL!");
            e.printStackTrace();
        } catch (IOException e) {
            //发生网络异常
            System.out.println("发生网络异常!");
        } finally {
            //6.释放连接
            getMethod.releaseConnection();
        }
        return response;
    }
 
    /**
     * post请求
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url, JSONObject json){
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
 
        postMethod.addRequestHeader("accept", "*/*");
        postMethod.addRequestHeader("connection", "Keep-Alive");
        //设置json格式传送
        postMethod.addRequestHeader("Content-Type", "application/json;charset=GBK");
        //必须设置下面这个Header
        postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        //添加请求参数
        postMethod.addParameter("commentId", json.getString("commentId"));
 
        String res = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            if (code == 200){
                res = postMethod.getResponseBodyAsString();
                System.out.println(res);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }
 
    public static void main(String[] args) {
        System.out.println(doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "GBK"));
        System.out.println("-----------分割线------------");
        System.out.println("-----------分割线------------");
        System.out.println("-----------分割线------------");
 
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("commentId", "13026194071");
        System.out.println(doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", jsonObject));
    }
}

실행 결과:

게시물에서 요청한 jsonObject의 매개변수도 성공적으로 작성되었습니다.

2.3 Apache로 캡슐화된 CloseableHttpClient

CloseableHttpClient Http 클라이언트의 수정 및 업데이트에 따라 여기에는 요청 헤더 토큰 설정(요청 확인)도 포함되며, 요청을 변환하거나 결과 문자열을 json 형식으로 반환하기 위해 fastjson을 사용합니다. 물론 위의 두 가지 방법을 설정할 수도 있습니다. 요청 헤더 토큰 및 json에 대해서는 아래에서만 설명합니다.

다음 jar 패키지를 가져옵니다.

<!--CloseableHttpClient-->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>
 
<!--fastjson-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.32</version>
</dependency>

코드는 다음과 같습니다.

package com.riemann.springbootdemo.util.common.httpConnectionUtil;
 
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
 
import java.io.IOException;
import java.io.UnsupportedEncodingException;
 
/**
 * @author riemann
 * @date 2019/05/25 1:35
 */
public class CloseableHttpClientUtil {
 
    private static String tokenString = "";
    private static String AUTH_TOKEN_EXPIRED = "AUTH_TOKEN_EXPIRED";
    private static CloseableHttpClient httpClient = null;
 
    /**
     * 以get方式调用第三方接口
     * @param url
     * @param token
     * @return
     */
    public static String doGet(String url, String token) {
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        if (null != tokenString && !tokenString.equals("")) {
            tokenString = getToken();
        }
        //api_gateway_auth_token自定义header头,用于token验证使用
        httpGet.addHeader("api_gateway_auth_token",tokenString);
        httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        try {
            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //返回json格式
                String res = EntityUtils.toString(response.getEntity());
                return res;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * 以post方式调用第三方接口
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url, JSONObject json) {
        if (null == httpClient) {
            httpClient = HttpClientBuilder.create().build();
        }
        HttpPost httpPost = new HttpPost(url);
        if (null != tokenString && tokenString.equals("")) {
            tokenString = getToken();
        }
        //api_gateway_auth_token自定义header头,用于token验证使用
        httpPost.addHeader("api_gateway_auth_token", tokenString);
        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        try {
            StringEntity se = new StringEntity(json.toString());
            se.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            se.setContentType("application/x-www-form-urlencoded");
            //设置请求参数
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //返回json格式
                String res = EntityUtils.toString(response.getEntity());
                return res;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpClient != null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
 
    /**
     * 获取第三方接口的token
     */
    public static String getToken() {
        String token = "";
        JSONObject object = new JSONObject();
        object.put("appid", "appid");
        object.put("secretkey", "secretkey");
        if (null == httpClient) {
            httpClient = HttpClientBuilder.create().build();
        }
        HttpPost httpPost = new HttpPost("http://localhost/login");
        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        try {
            StringEntity se = new StringEntity(object.toString());
            se.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            se.setContentType("application/x-www-form-urlencoded");
            //设置请求参数
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);
            //这里可以把返回的结果按照自定义的返回数据结果,把string转换成自定义类
            //ResultTokenBO result = JSONObject.parseObject(response, ResultTokenBO.class);
            //把response转为jsonObject
            JSONObject result = (JSONObject) JSONObject.parseObject(String.valueOf(response));
            if (result.containsKey("token")) {
                token = result.getString("token");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return token;
    }
 
    /**
     * 测试
     */
    public static void test(String telephone) {
 
        JSONObject object = new JSONObject();
        object.put("telephone", telephone);
 
        //首先获取token
        tokenString = getToken();
        String response = doPost("http://localhost/searchUrl", object);
        //如果返回的结果是list形式的,需要使用JSONObject.parseArray转换
        //List<Result> list = JSONObject.parseArray(response, Result.class);
        System.out.println(response);
    }
 
    public static void main(String[] args) {
        test("12345678910");
    }
}

2.4 SpringBoot-RestTemplate을 통해

springBoot-RestTemple은 위 세 가지 방법을 통합한 것이며, 현재 코드 작성이 더 간단합니다. 사용할 수 있는 파티 인터페이스는 다음과 같습니다.

Java를 사용하여 http 요청을 구현하는 방법delete()는 특정 URL의 리소스에 대해 HTTP DELETE 작업을 수행합니다.

exchange()는 URL에서 특정 HTTP 메서드를 실행하고 매핑된 개체가 포함된 ResponseEntity를 반환합니다. 응답 본문에서

execute( ) URL에서 특정 HTTP 메서드를 실행하고 응답 본문에서 매핑된 개체를 반환합니다.

getForEntity() HTTP GET 요청을 보내고 반환된 ResponseEntity에는 응답 본문에 매핑된 개체가 포함됩니다

getForObject() HTTP GET 요청을 보내면 반환된 요청 본문이 개체에 매핑됩니다.

postForEntity() POST 데이터를 URL로 보내고 개체가 포함된 ResponseEntity를 반환합니다. 이 개체는 응답 본문에서 매핑됩니다.

postForObject( ) URL에 대한 POST 데이터, 응답 본문 일치를 기반으로 형성된 개체를 반환합니다.

headForHeaders() HTTP HEAD 요청을 보내고 특정 리소스 URL이 포함된 HTTP 헤더를 반환합니다.

optionsForAllow() HTTP OPTIONS 요청을 보내고 허용을 반환합니다. 특정 URL에 대한 헤더 정보

postForLocation() POST 데이터를 URL에 보내고 새로 생성된 리소스의 URL을 반환합니다

put() PUT 리소스를 특정 URL

참고: 현재 굵은 글씨가 일반적으로 사용됩니다

먼저 springboot 웹 패키지를 가져옵니다

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>
 
    <dependencies>
        <!--CloseableHttpClient-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
 
        <!--spring restTemplate-->
        <!-- @ConfigurationProperties annotation processing (metadata for IDEs)
                生成spring-configuration-metadata.json类,需要引入此类-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

유사 패키지 시작 RestTemplateConfig.java 클래스

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
 
/**
 * @author riemann
 * @date 2019/05/25 2:16
 */
@Configuration
public class RestTemplateConfig {
 
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }
 
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(5000);
        return factory;
    }
}

를 생성한 다음 이를 Service 클래스(RestTemplateToInterface)에 삽입하여 사용합니다.

구체적인 코드는 다음과 같습니다.

import com.alibaba.fastjson.JSONObject;
import com.swordfall.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
 
/**
 * @author riemann
 * @date 2019/05/25 2:20
 */
@Service
public class RestTemplateToInterface {
 
    @Autowired
    private RestTemplate restTemplate;
 
    /**
     * 以get方式请求第三方http接口 getForEntity
     * @param url
     * @return
     */
    public User doGetWith2(String url){
        ResponseEntity<User> responseEntity = restTemplate.getForEntity(url, User.class);
        User user = responseEntity.getBody();
        return user;
    }
 
    /**
     * 以get方式请求第三方http接口 getForObject
     * 返回值返回的是响应体,省去了我们再去getBody()
     * @param url
     * @return
     */
    public User doGetWith3(String url){
        User user  = restTemplate.getForObject(url, User.class);
        return user;
    }
 
    /**
     * 以post方式请求第三方http接口 postForEntity
     * @param url
     * @return
     */
    public String doPostWith2(String url){
        User user = new User("小白", 20);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, user, String.class);
        String body = responseEntity.getBody();
        return body;
    }
 
    /**
     * 以post方式请求第三方http接口 postForEntity
     * @param url
     * @return
     */
    public String doPostWith3(String url){
        User user = new User("小白", 20);
        String body = restTemplate.postForObject(url, user, String.class);
        return body;
    }
 
    /**
     * exchange
     * @return
     */
    public String doExchange(String url, Integer age, String name){
        //header参数
        HttpHeaders headers = new HttpHeaders();
        String token = "asdfaf2322";
        headers.add("authorization", token);
        headers.setContentType(MediaType.APPLICATION_JSON);
 
        //放入body中的json参数
        JSONObject obj = new JSONObject();
        obj.put("age", age);
        obj.put("name", name);
 
        //组装
        HttpEntity<JSONObject> request = new HttpEntity<>(obj, headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
        String body = responseEntity.getBody();
        return body;
    }
}

2.5 okhttp를 통해

모든 분들의 반응에 부응하여 okhttp도 현재 휴대폰 기반으로 매우 인기가 높습니다. 여기서는 비즈니스 코드 가져오기 및 게시 요청을 직접 호출할 수 있는 OkHttpClient 클라이언트를 공유하겠습니다.

pom 파일에 종속성 패키지가 도입되었습니다

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.10.0</version>
</dependency>
@Slf4j
public class OkHttpClient {
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
 
    private volatile static okhttp3.OkHttpClient client;
 
    private static final int MAX_IDLE_CONNECTION = Integer
            .parseInt(ConfigManager.get("httpclient.max_idle_connection"));
 
    private static final long KEEP_ALIVE_DURATION = Long
            .parseLong(ConfigManager.get("httpclient.keep_alive_duration"));
 
    private static final long CONNECT_TIMEOUT = Long.parseLong(ConfigManager.get("httpclient.connectTimeout"));
 
    private static final long READ_TIMEOUT = Long.parseLong(ConfigManager.get("httpclient. "));
 
    /**
     * 单例模式(双重检查模式) 获取类实例
     *
     * @return client
     */
    private static okhttp3.OkHttpClient getInstance() {
        if (client == null) {
            synchronized (okhttp3.OkHttpClient.class) {
                if (client == null) {
                    client = new okhttp3.OkHttpClient.Builder()
                            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                            .connectionPool(new ConnectionPool(MAX_IDLE_CONNECTION, KEEP_ALIVE_DURATION,
                                    TimeUnit.MINUTES))
                            .build();
                }
            }
        }
        return client;
    }
 
    public static String syncPost(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try {
            Response response = OkHttpClient.getInstance().newCall(request).execute();
            if (response.isSuccessful()) {
                String result = response.body().string();
                log.info("syncPost response = {}, responseBody= {}", response, result);
                return result;
            }
            String result = response.body().string();
            log.info("syncPost response = {}, responseBody= {}", response, result);
            throw new IOException("三方接口返回http状态码为" + response.code());
        } catch (Exception e) {
            log.error("syncPost() url:{} have a ecxeption {}", url, e);
            throw new RuntimeException("syncPost() have a ecxeption {}" + e.getMessage());
        }
    }
 
    public static String syncGet(String url, Map<String, Object> headParamsMap) throws IOException {
        Request request;
        final Request.Builder builder = new Request.Builder().url(url);
        try {
            if (!CollectionUtils.isEmpty(headParamsMap)) {
                final Iterator<Map.Entry<String, Object>> iterator = headParamsMap.entrySet()
                        .iterator();
                while (iterator.hasNext()) {
                    final Map.Entry<String, Object> entry = iterator.next();
                    builder.addHeader(entry.getKey(), (String) entry.getValue());
                }
            }
            request = builder.build();
            Response response = OkHttpClient.getInstance().newCall(request).execute();
            String result = response.body().string();
            log.info("syncGet response = {},responseBody= {}", response, result);
            if (!response.isSuccessful()) {
                throw new IOException("三方接口返回http状态码为" + response.code());
            }
            return result;
        } catch (Exception e) {
            log.error("remote interface url:{} have a ecxeption {}", url, e);
            throw new RuntimeException("三方接口返回异常");
        }
    }
 
}

위 내용은 Java를 사용하여 http 요청을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제