java如何根据PostMan发送请求设置接口请求工具类

 更新时间:2024年09月24日 09:13:36   作者:Dubbo-罗  
在Java中调用第三方接口可以通过不同的方式,如使用GET、POST等请求,关键点包括设置正确的请求方式、URL、参数(params)、头信息(headers)和请求体(body),对于不同的数据格式,如XML和JSON,需在header中声明内容类型

java根据PostMan发送请求:设置接口请求工具类

我们使用java代码进行接口远程调用第三方接口时,总会抒写接口代码,那么有这么多种方式进行发送请求。那我们应该怎么使用呢?

比如有webservice接口,比如有Post请求的接口,必须有Get请求的接口。比如传的参数有xml的形式,比如传的参数有json格式等等格式情况,那我们的接口请求代码应该如何区别,抒写呢?

我们要根据postMan中的方式来,只要是能够通过postMan发送成功的请求都可以使用

首先是我们的请求方式

第一点:在postMan的请求方式有:GET、POST、PUT、DELETE请求。

第二点:在PostMan中我们需要传入url链接,那么new HttpGet(url)这里面的url就是链接地址。

GET:HttpGet httpGet = new HttpGet(url);
POST:HttpPost method = new HttpPost(url);
PUT:HttpPut put = new HttpPut(url);
DELETE:HttpDelete delete = new HttpDelete(url);

第三点:在PostMan中我们需要Params的时候:

HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter("","");
httpParams.setParameter("","");
httpParams.setParameter("","");
method.setParams(httpParams);

第四点:在PostMan中我们需要设置Headers,其中方token或者字节编码的时候很使用。

HttpPost method = new HttpPost(url);
method.addHeader("","");
method.addHeader("","");
method.addHeader("","");

第五点:在PostMan中我们需要设置Body,其中需要传入参数,不管是xml还是json都可以。那么我们需要设置两个地方。

1、在第四点中的header中需要设置传入参数的是xml还是json:

method.addHeader("Content-Type","application/json;");这里是json
method.addHeader("Content-Type","application/xml;");这里是xml

2、在传回来的参数中我们需要设置返回的数据类型和字符编码集:param是发送的body参数。

StringEntity entity = new StringEntity(param, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json;");
method.setEntity(entity);//放入到method请求中。

第六点:这样进行发送请求:method是集合请求方式,Params,Headers,body参数以后的集合。然后进行发送。

CloseableHttpClient httpClient = HttpClients.createDefault();//得到发送。
 HttpResponse resultRep = httpClient.execute(method);

第七点:在PostMan中返回的数据,我们需要如下来接收:

/请求发送成功,并得到响应/

 if (resultRep.getStatusLine().getStatusCode() == 200) {
     String str = "";
     /**读取服务器返回过来的json字符串数据**/
     log.info("=========测试"+resultRep.toString());
     String str4 = EntityUtils.toString(resultRep.getEntity());
     log.info("========str4"+str4);
     result = str4;
 }

举例如下

第一种方法:

 public static String getwebserviceNew(String method,String serviceUrl,String user,String pw,String param){
        try {
        //第一步:选择请求方式:
            PostMethod postMethod = null;
            postMethod = new PostMethod();
            postMethod.setPath(serviceUrl);
            String auth = "bearer "+pw;
      	//第二步:设置header参数
            postMethod.addRequestHeader("Authorization", auth);
            postMethod.setRequestHeader("Content-Type", "text/xml") ;
        //第三步:得到需要发送的body
            String xmlInfo = getXmlInfo(method,user,pw,param);
		//第四步:设置发送的参数编码集:
            postMethod.setRequestEntity(new StringRequestEntity(xmlInfo.toString(),"application/xml","UTF-8"));
            org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
        //第五步:发送请求:
            int response = httpClient.executeMethod(postMethod); // 执行POST方法
            log.info("response--接口状态码-->"+response);
            String result = postMethod.getResponseBodyAsString() ;
            log.info("result-接口返回值-->"+result);
            return result;
        } catch (Exception e) {
            log.info("e----->"+e);
            //logger.info("请求异常"+e.getMessage(),e);
            throw new RuntimeException(e.getMessage());
        }
    }

    private static String getXmlInfo(String method,String fydm,String token,String xml) {
        StringBuilder sb = new StringBuilder();
        sb.append("<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:szft='http://szft.tdh/'>");
        sb.append("<soapenv:Header/>");
        sb.append("<soapenv:Body>");
        sb.append("<szft:"+method+">");
        sb.append("<fydm>"+fydm+"</fydm>");
        sb.append("<token>"+token+"</token>");
        sb.append("<xml>"+xml+"</xml>");
        sb.append("</szft:"+method+">");
        sb.append("</soapenv:Body>");
        sb.append("</soapenv:Envelope>");
        return sb.toString();
    }

第二种方法:

    /**
     * http请求接口,获取通达海token和获取通达海代理人使用
     * post请求
     * @param url         url地址
     * @param param     请求参数
     * @param token     token
     * @param ContentType     发送数据类型
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String httpPostAllAgent(String url,String param,String token,String ContentType) throws ClientProtocolException, IOException{

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        url = URLDecoder.decode(url, "UTF-8");
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = null;
        HttpPost method = new HttpPost(url);
        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put("Content-Type", ContentType);
        headers.put("Accept-Charset", "charset=utf-8");
        headers.put("Authorization", token);
        for (Map.Entry<String, Object> head : headers.entrySet()) {
            method.addHeader(head.getKey(), String.valueOf(head.getValue()));
        }
        //设置请求访问时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000*60).setConnectTimeout(1000*60).build();//设置请求和传输超时时间
        method.setConfig(requestConfig);

        if (null != param) {
            StringEntity entity = new StringEntity(param, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType(ContentType);
            method.setEntity(entity);
        }
        HttpResponse resultRep = httpClient.execute(method);
        /**请求发送成功,并得到响应**/
        if (resultRep.getStatusLine().getStatusCode() == 200) {
            String str = "";
            /**读取服务器返回过来的json字符串数据**/
            log.info("=========测试"+resultRep.toString());
            String str4 = EntityUtils.toString(resultRep.getEntity());
            log.info("========str4"+str4);
            result = str4;
        }
        return result;
    }

multipart/form-data请求方式:

    public static String uploadFile(String url, Map<String, Object> mapData){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        //每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。
        String boundary ="----WebKitFormBoundary5ZMULAAn6mngkXzn";
        try {
            HttpPost httpPost = new HttpPost(url);
            //设置请求头
            httpPost.setHeader("Content-Type","multipart/form-data; boundary="+boundary);
            //HttpEntity builder
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            //字符编码
            builder.setCharset(Charset.forName("UTF-8"));
            //模拟浏览器
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            //boundary
            builder.setBoundary(boundary);
            //multipart/form-data
//            builder.addPart("multipartFile",new FileBody(filePath));
            // binary
//            builder.addBinaryBody("name=\"multipartFile\"; filename=\"test.docx\"", new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
//            //其他参数
            for (String key : mapData.keySet()) {
                builder.addTextBody(key, mapData.get(key).toString(),  ContentType.create("text/plain", Consts.UTF_8));
            }
            //HttpEntity
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            // 执行提交
            HttpResponse response = httpClient.execute(httpPost);
            //响应
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.err.println("result"+result);
        return result;
    }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • java代码审计之目录遍历的解决

    java代码审计之目录遍历的解决

    目录穿越漏洞,也叫做目录遍历/路径遍历漏洞,本文主要介绍了java代码审计之目录遍历的解决,文中通过案例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-06-06
  • Java中Math.round()的用法及说明

    Java中Math.round()的用法及说明

    这篇文章主要介绍了Java中Math.round()的用法及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-02-02
  • 浅谈java 单例模式DCL的缺陷及单例的正确写法

    浅谈java 单例模式DCL的缺陷及单例的正确写法

    这篇文章主要介绍了浅谈java 单例模式DCL的缺陷及单例的正确写法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • 深入理解jvm启动参数

    深入理解jvm启动参数

    JVM的启动参数是在启动JVM时可以设置的一些命令行参数,本文详细的介绍了深入理解jvm启动参数,具有一定的参考价值,感兴趣的可以了解一下
    2023-08-08
  • springboot日志文件名称叫logback-spring.xml的原因解析

    springboot日志文件名称叫logback-spring.xml的原因解析

    这篇文章主要介绍了springboot日志文件名称为什么叫logback-spring.xml,本文给大家讲解的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-08-08
  • Java中一些关键字的使用技巧总结

    Java中一些关键字的使用技巧总结

    这篇文章主要介绍了Java中一些关键字的使用技巧总结,其中重点讲述了this和super两个关键字的用法,需要的朋友可以参考下
    2015-09-09
  • Springboot logback-spring.xml无法加载问题

    Springboot logback-spring.xml无法加载问题

    这篇文章主要介绍了Springboot logback-spring.xml无法加载问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-05-05
  • SpringBoot使用Validator进行参数校验实战教程(自定义校验,分组校验)

    SpringBoot使用Validator进行参数校验实战教程(自定义校验,分组校验)

    这篇文章主要介绍了SpringBoot使用Validator进行参数校验(自定义校验,分组校验)的实战教程,本文通过示例代码给大家介绍的非常详细,需要的朋友参考下吧
    2023-07-07
  • IDEA POJO开发神器之Groovy的使用详解

    IDEA POJO开发神器之Groovy的使用详解

    这篇文章主要介绍了IDEA POJO开发神器之Groovy的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-07-07
  • idea打包java可执行jar包的实现步骤

    idea打包java可执行jar包的实现步骤

    这篇文章主要介绍了idea打包java可执行jar包的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12

最新评论