首页 > 编程语言 >java中的远程调用http

java中的远程调用http

时间:2024-04-09 21:36:07浏览次数:26  
标签:调用 java String try httpPost http null response httpClient

分享一下项目中用过的远程调用方法并总结两种请求方式的差别

 http远程调用一般分为两种 get和post(其它方式暂不考虑)

pom包

<!--http远程调用-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.9</version>
        </dependency>

 

get请求方式

/**
     * 发送get请求
     * authorization为请求token(不需要可以去掉)
     */
    public static String get(String url,String authorization) {
        String res;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Authorization", authorization);
            res = execute(httpClient, httpGet);
        } finally {
            doHttpClientClose(httpClient);
        }
        return res;
    }

    private static String execute(CloseableHttpClient httpClient, HttpUriRequest httpGetOrPost) {
        String res = null;
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGetOrPost);
            HttpEntity entity = response.getEntity();
            res = EntityUtils.toString(entity, CHARSET_UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            doResponseClose(response);
        }
        return res;
    }

    /**
     * httpClient关闭
     */
    private static void doHttpClientClose(CloseableHttpClient httpClient) {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * response关闭
     */
    private static void doResponseClose(CloseableHttpResponse response) {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

get我觉得通篇下来就是url比较重要,其它的都是一些常规方法,因为get方法基本是在url上拼参数

String url = "127.0.0.1:8080/api/personList?pageNum=1&pageSize=10&idcardNo="+idCard;

 

post请求方法

  post的请求方式就多种多样了 application/json、application/x-www-form-urlencoded、application/form-data

 

这里是一个post请求方法

Map<String, String> header = new HashMap<>();
 header.put("Accept", "*/*");
 header.put("Content-Type", "application/x-www-form-urlencoded");


 /**
   * 设置超时时间及重试次数
   */
  private static final int retryCount = 3;
  private static final RequestConfig requestConfig = RequestConfig.custom()
        .setSocketTimeout(15000)
        .setConnectTimeout(15000)
        .setConnectionRequestTimeout(15000)
        .build();


  /**
     * 通用型httpPost调用
     */
    public static String post(final String url, Map<String, String> map, final Map<String, String> headParam) {
        final CloseableHttpClient httpClient =  HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        int index = 0;
        final HttpPost httpPost = new HttpPost(url);
        try {
            //将头部header参数写进httpPost的header中
            if (headParam != null) {
                for (final String key : headParam.keySet()) {
                    httpPost.setHeader(key, headParam.get(key));
                }
            }
            httpPost.setHeader("Authorization", "admin");
            //将外部参数写进params中(这里也是一个个去写入,理论上application/form-data也是这种写入方式)
            List<NameValuePair> params = new ArrayList<>();
            if(map!=null){
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            //设置参数到请求对象中
            httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            httpPost.setConfig(requestConfig);
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        }
        catch (Exception e) {
            while(null == response && index < retryCount){
                log.info("第 {} 次重试", index + 1);
                try {
                    response = httpClient.execute(httpPost);
                } catch (Exception e1) {
                    log.error("报错结果:", e1);
                }
                index++;
            }
            try {
                assert response != null;
                response.close();
            }
            catch (IOException e2) {
                e2.printStackTrace();
            }
        }
        finally {
            try {
                assert response != null;
                response.close();
            }
            catch (IOException e3) {
                e3.printStackTrace();
            }
        }
        return resultString;
    }

 

application/json其实只是换下写入参数的方法


//设置请求头
httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
httpPost.setHeader("Accept", "*/*");
   
/**
* 通用型httpPost调用
*/
public static String post(final String url, JSONObject param, final Map<String, String> headParam) {
final CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
int index = 0;
final HttpPost httpPost = new HttpPost(url);
try {
//将头部header参数写进httpPost的header中
if (headParam != null) {
for (final String key : headParam.keySet()) {
httpPost.setHeader(key, headParam.get(key));
}
}
httpPost.setHeader("Authorization", "admin");
//将整体参数变成json传进去(这里与上面方法会有区别)
if (EmptyUtils.isNotEmpty(param)) {
httpPost.setEntity(new StringEntity(param.toJSONString(), StandardCharsets.UTF_8));
}

httpPost.setConfig(requestConfig);
response = httpClient.execute(httpPost);

resultString = EntityUtils.toString(response.getEntity(), "utf-8");
}
catch (Exception e) {
while(null == response && index < retryCount){
log.info("第 {} 次重试", index + 1);
try {
response = httpClient.execute(httpPost);
} catch (Exception e1) {
log.error("报错结果:", e1);
}
index++;
}
try {
assert response != null;
response.close();
}
catch (IOException e2) {
e2.printStackTrace();
}
}
finally {
try {
assert response != null;
response.close();
}
catch (IOException e3) {
e3.printStackTrace();
}
}
return resultString;
}

参数用JSONObject param传递感觉还是不太方便

得一个个写参数封装进param

JSONObject param = new JSONObject(); Map<String, Object> map = new HashMap<>(); map.put("name", "123"); map.put("phone", "1234"); param.put("params", map);

因为传参数我一般习惯用实体类传参(特别是参数比较多的情况)

用Object object传参,不管你传过来的参数是map还是JSONObject还是实体类

/**
     * 通用型httpPost调用
     */
    public static String post(final String url, final Object object, final Map<String, String> headParam) {
        final CloseableHttpClient httpClient =  HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        int index = 0;
        final HttpPost httpPost = new HttpPost(url);
        try {
            //将头部header参数写进httpPost的header中
            if (headParam != null) {
                for (final String key : headParam.keySet()) {
                    httpPost.setHeader(key, headParam.get(key));
                }
            }
            httpPost.setHeader("Authorization", "admin");

            //这里将传过来的object参数转成JSONObject(多了这一步)
            String json = JSONObject.toJSONString(object);
            JSONObject jsonObject = JSONObject.parseObject(json);
            
            //将整体参数变成json传进去
            if (EmptyUtils.isNotEmpty(object)) {
                httpPost.setEntity(new StringEntity(jsonObject.toString(), StandardCharsets.UTF_8));
            }

            httpPost.setConfig(requestConfig);
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        }
        catch (Exception e) {
        //这里逻辑不用管,因为有设置超时时间和重试次数,不需要这里逻辑可忽略 while(null == response && index < retryCount){ log.info("第 {} 次重试", index + 1); try { response = httpClient.execute(httpPost); } catch (Exception e1) { log.error("报错结果:", e1); } index++; } try { assert response != null; response.close(); } catch (IOException e2) { e2.printStackTrace(); } } finally { try { assert response != null; response.close(); } catch (IOException e3) { e3.printStackTrace(); } } return resultString; }

关于get、post请求远程调用的就讲完了

还有一些调用遇到的例子也给大家分享下

忽略ssl证书警告(有些接口可能配置了https)

 

方法不可完全复制,如果需要,将忽略ssl证书警告方法放到上面方法稍微修改下

 static CloseableHttpClient httpClient;

    /**
     * 忽略ssl证书警告
     */
    public static CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 信任所有
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }

    /**
     * 根据token查询接口
     */
    public static String doPost(final String url, final Object object, String token) {
        int index = 0;
        final CloseableHttpClient httpclient =  HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            //设置httpPost
            HttpPost httpPost = setHttpPost(url, object);
            httpPost.setHeader("Authorization", token);
            httpPost.setConfig(requestConfig);
            try {
          //主要是这里先调用忽略ssl证书的方法后才去调用远程接口 httpClient = createSSLClientDefault(); response = httpClient.execute(httpPost); } catch (SocketTimeoutException e) { while(null == response && index < retryCount){ log.error("第 {} 次重试, url:{}", index + 1, url); try { response = httpclient.execute(httpPost); } catch (Exception e1) { log.error("第 {} 次重试结果, e:{}", index + 1, e1.getMessage()); } index++; log.info("SocketTimeoutException结果: e{}", e.getMessage()); } } //解析返回数据 assert response != null; resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (Exception e) { log.info("Exception结果: url:{}, e:{}", url, e.getMessage()); //如果异常为自定义异常则主动抛出 if (e instanceof BizException) { try { throw e; } catch (IOException ex) { ex.printStackTrace(); } } closeResponse(response); } finally { closeResponse(response); } return resultString; }

 



 

标签:调用,java,String,try,httpPost,http,null,response,httpClient
From: https://www.cnblogs.com/magepi/p/18124770

相关文章

  • python调用opencv提示“Rebuild the library with Windows, GTK+ 2.x or Cocoa suppor
    windows下python调用opencv,提示以下问题:cv2.error:OpenCV(4.9.0)D:\a\opencv-python\opencv-python\opencv\modules\highgui\src\window.cpp:1272:error:(-2:Unspecified error)Thefunctionisnotimplemented.RebuildthelibrarywithWindows,GTK+2.xorCocoa......
  • 03-JAVA设计模式-适配器模式
    适配器模式设么是适配器模式它属于结构型模式,主要用于将一个类的接口转换成客户端所期望的另一种接口,从而使得原本由于接口不兼容而无法协同工作的类能够一起工作。适配器模式主要解决的是不兼容接口的问题。在软件开发中,经常会有这样的情况:我们有一个现有的类,它的接口(方......
  • 基于JAVA Springboot + Vue 前端后分离 实现【考研资讯平台】(内附设计LW + PPT+ 源码
    项目名称项目名称:考研资讯平台项目技术栈该项目采用了以下核心技术栈:后端框架/库:SpringBoot数据库:MySQL前端技术:Vue.js(前后端分离)项目展示5.1学生前台功能模块5.1.2首页在系统首页可以查看以下内容:首页考研资讯报考指南资料信息论坛信息我的跳转到后台购物......
  • 基于JAVA Springboot + Vue 前端后分离 实现【教师人事档案管理系统】(内附设计LW + PP
    项目名称项目名称:教师人事档案管理系统项目技术栈该项目采用了以下核心技术栈:后端框架/库:Java数据库:MySQL前端技术:Vue.js(前后端分离)开发工具:Eclipse项目展示5.1前台功能模块前台首页在教师人事档案管理系统首页可以查看以下内容:首页培训信息系统公告个人中心......
  • 《架构风清扬-Java面试系列第19讲》解释一下Java中的“volatile”在多线程环境中的作
    适用范围:这道题适应范围挺宽的,各个年限都可以用参考答案:主要用于确保变量在多个线程之间的可见性和有序性。可见性:当一个线程修改了被volatile修饰的变量,其他线程能够立即看到修改后的值。这确保了变量在多个线程之间的可见性。有序性:volatile关键字能够防止指令重排序......
  • 最长公共子序列(线性dp)-java
    本文主要来描述两个字符串的最长公共子序列问题文章目录前言一、最长公共子序列二、算法思路1.dp[i][j]的四种情况2.dp[i-1][j]、dp[i][j-1]、dp[i-1][j-1]的关系3.dp数组的状态转移方程 4.dp数组具体如下三、代码如下1.代码如下(示例):2.读入数据3.代码运行结......
  • Java基础知识-面向对象编程(OOP)-Java集合框架-多线程和并发-Spring框架
    Java基础知识:Java的四种基本数据类型是:byte、short、int、long(整数类型)、float、double(浮点类型)、char(字符类型)、boolean(布尔类型)。它们之间的区别主要在于占用的内存大小和表示范围不同。Java中的String是不可变的意味着一旦String对象被创建,它的值就不能被修改。这意味着St......
  • Java IO与NIO-Java内存管理-Java虚拟机(JVM)-Java网络编程-Java注解(Annotation)
    JavaIO与NIO:请解释Java中的IO(Input/Output)和NIO(NewInput/Output)的区别是什么?它们各自的优势是什么?答案:Java中的IO是基于流(Stream)的方式进行输入输出操作,而NIO则是基于通道(Channel)和缓冲区(Buffer)的方式进行输入输出操作。NIO相比于IO具有非阻塞IO、选择器(Selector)和内存映......
  • Java——继承(含习题)
    继承的概念定义面向对象的继承,指在由一般类和特殊类形成的“一般-特殊”之间的类结构中,把一般类和所有特殊类都共同具有的属性和操作一次性地在一般类中进行定义,特殊类不再重复定义一般类已经定义的属性和操作,特殊类自动拥有一般类(以及所有更上层的一般类)定义的属性和操作......
  • Java登陆第四十一天——Axios
    Vue推荐使用axios来完成ajax请求。axios中文文档AxiosAxios是一款基于Promise,用于发送HTTP请求和处理HTTP响应的工具库。内部也是使用原生的ajax对象发送HTTP请求。所以,在使用它前需要导入依赖。npminstallaxios提供了一个函数:axios()语法格式如下://查看源码,默认......