Java的HTTP调用简述

调用对方提供的接口

①通过JDK网络类Java.net.HttpURLConnection;

②通过common封装好的HttpClient;

③通过Apache封装好的CloseableHttpClient;

④通过SpringBoot-RestTemplate;

RestTemplate

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;
 
@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;
    }
}
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;
 
@Service
public class RestTemplateToInterface {
 
    @Autowired
    private RestTemplate restTemplate;
 
    /**
     * 以get方式请求第三方http接口 getForEntity
     * @param url
     * @return
     */
    public User doGetWith1(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 doGetWith2(String url){
        User user  = restTemplate.getForObject(url, User.class);
        return user;
    }
 
    /**
     * 以post方式请求第三方http接口 postForEntity
     * @param url
     * @return
     */
    public String doPostWith1(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 doPostWith2(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;
    }
}

delete() : 在特定的URL上对资源执行HTTP DELETE操作
exchange() : 在URL上执行特定的HTTP方法,返回包含对象的ResponseEntity,这个对象是从响应体中映射得到的
execute() : 在URL上执行特定的HTTP方法,返回一个从响应体映射得到的对象
getForEntity() :发送一个HTTP GET请求,返回的ResponseEntity包含了响应体所映射成的对象
getForObject() :发送一个HTTP GET请求,返回的请求体将映射为一个对象
postForEntity() :POST 数据到一个URL,返回包含一个对象的ResponseEntity,这个对象是从响应体中映射得到的
postForObject(): POST 数据到一个URL,返回根据响应体匹配形成的对象
headForHeaders() :发送HTTP HEAD请求,返回包含特定资源URL的HTTP头
optionsForAllow() :发送HTTP OPTIONS请求,返回对特定URL的Allow头信息
postForLocation() :POST 数据到一个URL,返回新创建资源的URL
put() :PUT 资源到特定的URL

JDK网络类Java.net.HttpURLConnection

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpUrlConnectionToInterface {
 
    /**
     * 以post或get方式调用对方接口方法,
     * @param pathUrl
     */
    public static void doPostOrGet(String pathUrl, String data){
        OutputStreamWriter out = null;
        BufferedReader br = null;
        String result = "";
        try {
            URL url = new URL(pathUrl);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //请求方式
            conn.setRequestMethod("POST");
            //conn.setRequestMethod("GET");
 
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
 
            //DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
            conn.setDoOutput(true);
            conn.setDoInput(true);
 
            /**
             * 下面的三句代码,就是调用第三方http接口
             */
            //获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            //发送请求参数即数据
            out.write(data);
            //flush输出流的缓冲
            out.flush();
 
            /**
             * 下面的代码相当于,获取调用第三方http接口后返回的结果
             */
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null){
                result += str;
            }
            System.out.println(result);
            //关闭流
            is.close();
            //断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
            conn.disconnect();
 
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (out != null){
                    out.close();
                }
                if (br != null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    public static void main(String[] args) {
        /**
         *手机信息查询接口:http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=手机号
     *      http://api.showji.com/Locating/www.showji.com.aspx?m=手机号&output=json&callback=querycallback
         */
        doPostOrGet("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "");
    }
}

apache common封装好的HttpClient

(1)httpClient的get或post请求方式步骤

生成一个HttpClient对象并设置相应的参数;
生成一个GetMethod对象或PostMethod并设置响应的参数;
用HttpClient生成的对象来执行GetMethod生成的Get方法;
处理响应状态码;
若响应正常,处理HTTP响应内容;
释放连接。
(2)导入如下jar包

   <!--HttpClient-->
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>版本自己定义</version>
        </dependency>
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;
import java.io.InputStream;
public class HttpClientToInterface {
 
    /**
     * 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=utf-8");
        //必须设置下面这个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) {
        doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=1234567890", "UTF-8");
 
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("commentId", "1234567890");
        doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=1234567890", jsonObject);
    }
}

Apache封装好的CloseableHttpClient

参考资料:https://blog.csdn.net/RuiKe1400360107/article/details/107487976

Spring Boot 整合feign调用远程http接口

Spring Cloud Feign(现称为 OpenFeign)是一个声明式的 HTTP 客户端。它让编写 HTTP 客户端变得更加简单,类似于调用本地方法一样调用远程服务。
Feign 是一个声明式的 Web 服务客户端。使用 Feign,只需要创建一个接口并注解即可。它可以与 Eureka 和 Ribbon 集成,以便自动发现服务和负载均衡请求。
主要特性
声明式 HTTP 客户端:通过注解和接口定义 API,简化了 HTTP 请求的调用。
负载均衡:结合 Ribbon 可以实现客户端的负载均衡。
服务发现:结合 Eureka 实现服务自动发现。
可插拔的编解码器:可以自定义序列化和反序列化机制。
集成 Hystrix:支持断路器模式,提供熔断和降级功能。
使用场景
微服务间调用:在微服务架构中,服务之间的调用变得频繁。Feign 通过声明式接口的方式简化了这种调用。
负载均衡与服务发现:结合 Ribbon 和 Eureka,Feign 可以实现负载均衡和服务发现,使服务调用更加高效和可靠。
简化 HTTP 请求:对于需要频繁进行 HTTP 请求的场景,Feign 提供了一种更优雅的解决方案,通过注解来定义请求方式和参数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值