首页 > 编程语言 >使用Java调用RestFul接口的几种方法

使用Java调用RestFul接口的几种方法

时间:2022-10-09 18:25:19浏览次数:43  
标签:Java String url 接口 new null RestFul response conn

使用Java调用RestFul接口的几种方法

 

1. HttpURLConnection

public String postRequest(String url, String param) {
    StringBuffer result = new StringBuffer();

    HttpURLConnection conn = null;
    OutputStream out = null;
    BufferedReader reader = null;
    try {
        URL restUrl = new URL(url);
        conn = (HttpURLConnection) restUrl.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);

        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");

        conn.connect();
        out = conn.getOutputStream();
        out.write(param.getBytes());
        out.flush();

        int responseCode = conn.getResponseCode();
        if(responseCode != 200){
            throw new RuntimeException("Error responseCode:" + responseCode);
        }

        String output = null;
        reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
        while((output=reader.readLine()) != null){
            result.append(output);
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("调用接口出错:param+"+param);
    } finally {
        try {
            if(reader != null){
                reader.close();
            }
            if(out != null){
                out.close();
            }
            if(conn != null){
                conn.disconnect();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }

    return result.toString();
}

 

2. HttpClient方式

public class HttpClientUtil {

    public String post(String url, Map<String, Object> pramMap) throws Exception {
        String result = null;
        // DefaultHttpClient已过时,使用CloseableHttpClient替代
        CloseableHttpClient closeableHttpClient = null;
        CloseableHttpResponse response = null;
        try {
            closeableHttpClient = HttpClients.createDefault();
            HttpPost postRequest = new HttpPost(url);
            List<NameValuePair> pairs = new ArrayList<>();
            if(pramMap!=null && pramMap.size() > 0){
                for (Map.Entry<String, Object> entry : pramMap.entrySet()) {
                    pairs.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
                }
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs, "utf-8");
            postRequest.setEntity(formEntity);

            response = closeableHttpClient.execute(postRequest);
            if(response!=null && response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
                result = EntityUtils.toString(response.getEntity(), "utf-8");
            }else{
                throw new Exception("post请求失败,url" + url);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                if(response != null){
                    response.close();
                }
                if(closeableHttpClient != null){
                    closeableHttpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

}

 

3.  spring提供的RestTemplate模板方式

public class RestTemplateUtil {
 
    @Bean
    public RestTemplate restTemplate(){
        RestTemplate template = new RestTemplate();
        // messageConverters是RestTemplate的一个final修饰的List类型的成员变量
        // messageConverters的第二个元素存储的是StringHttpMessageConverter类型的消息转换器
        // StringHttpMessageConverter的默认字符集是ISO-8859-1,在此处设置utf-8字符集避免产生乱码
        template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("utf-8")));
        return template;
    }
 
    @Autowired
    private RestTemplate restTemplate;
 
    public String post(String url, String jsonParam){
        // 自定义请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAcceptCharset(Collections.singletonList(Charset.forName("utf-8")));
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
 
        // 参数
        HttpEntity<String> entity = new HttpEntity<String>(jsonParam, headers);
        // POST方式请求
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        if(responseEntity == null){
            return null;
        }
 
        return responseEntity.getBody().toString();
    }
 
}

 

Reference

https://www.cnblogs.com/liuyb/p/11202004.html

https://www.cnblogs.com/lukelook/p/11169219.html

标签:Java,String,url,接口,new,null,RestFul,response,conn
From: https://www.cnblogs.com/pugang/p/16773181.html

相关文章

  • Java入门,如何高效学习
      对于当下要想入行学习Java,那就一定是个不错的选择,因为这个行业是个你只要努力就能看到成果的行业,而且就从近两年来看,当前的程序员依旧是这个时代的高薪职业,且想要入这......
  • javaweb文件上传和下载
    案例1:文件随同表单一起上传前端页面<div><formclass="form-signin"id="addSongFormId"enctype="multipart/form-data"method="post">歌曲:<inputtype="file"id="fileS......
  • 通过JAVA客户端远程安装系统挂载镜像失败
    问题:通过JAVA客户端远程安装系统挂载镜像失败现象:因业务需要通过BMC系统远程给服务器重装系统,使用KVM方式远控时,挂载镜像失败,点击“虚拟介质”-“虚拟介质向导”后直接闪......
  • 桥接模式——Java实现
    问题描述:用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。类图:  Java源代码://Road.javapackageshiyan9;publicabstractcla......
  • 日期类java.util.Date
    1packagecom.msb.test02;23importjava.util.Date;45/**6*开发人:liu7*日期:15:41:058*描述:IntelliJIDEA9*版本:1.010*/11pub......
  • java连接接kerberos认证下的hive
    1.pop.xml配置hive与hadoop的配置版本要匹配,一般hive2.X版本要选择hadoop2.x版本,否则会不兼容<dependency><groupId>org.apache.hadoop</groupId>......
  • 18_Java中的内部类
    Java的内部类一、内部类概述1、内部类:其实就是在一个类中定义一个类(类似于C语言中的结构体的嵌套)2、定义格式:publicclass类名{修饰符class类名{......
  • Java加解密-SM4国密算法
    SM4国密算法简介SM4依赖包SM4类SM4_Context类SecuritySM4类=================================== SM4国密算法简介与DES和AES算法相似,国密SM4算法是一种分组加密......
  • Java 多线程(三)静态代理模式
    静态代理模式:1.真实角色和代理角色实现同一个接口2.代理角色要代理真实角色3.代理角色可以做真实角色做不了的事4.真实角色专注做自己的事publicclassStaticProxy......
  • Java开发页面接口过程中,应该注意的点
    列表接口1、查询条件是否需要去除前后空格;2、列表的时间格式是否正确;有的显示2022-07-28这种格式,有的显示:2022-07-2719:00:003、在前端传递时间的参数时,若定义的是Da......