java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java远程调用接口URL

java远程调用接口、URL的方式代码

作者:随意石光

我们都知道接口有自己本地的,也有远程别人写好的,而调用远程接口的就需要使用远程调用啦,这篇文章主要给大家介绍了关于java远程调用接口、URL的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下

一:httpUrlConnection

1.获取HttpURLConnection连接对象

   /**
     * 获取HttpURLConnection连接对象
     * @param url 远程调用的url
     * @return
     */
    public static HttpURLConnection getHttpURLConnection(String url){
        try {
            //建立连接
            URL httpUrl = new URL(url);
            HttpURLConnection urlConnection =(HttpURLConnection)httpUrl.openConnection();
            //向文件所在服务器发送标识信息,模拟浏览器
            urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36");
            return urlConnection;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

2.远程调用代码

/**
     * 远程调用登录接口
     */
    public void accessLoginUrl(){
        //远程调用接口的url
        String loginUrl = "http://localhost:8989/login/doLogin";
        OutputStream outputStream = null;
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            //获取压测接口的userTicket
            URL url = new URL(loginUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //登录是post请求
            connection.setRequestMethod("POST");
            //post请求需要设置接口返回的数据,所以设置为true
            connection.setDoOutput(true);
            //参数userId和密码
            String param = "mobile=" + 13100000000000L + "&password=" + "123456";
            //获取登录接口返回的流文件
            outputStream = connection.getOutputStream();
            outputStream.write(param.getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
            inputStream = connection.getInputStream();
            byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) >= 0){
                byteArrayOutputStream.write(buffer, 0, len);
            }
            //获取响应结果
            String response = byteArrayOutputStream.toString();
            ObjectMapper objectMapper = new ObjectMapper();
            RespBean respBean = objectMapper.readValue(response, RespBean.class);
            String userTicket = (String) respBean.getObject();
            System.out.println("远程调用接口的返回值"+userTicket);
            //userTicket就是远程接口返回的值
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(byteArrayOutputStream != null){
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

二:RestTemplate

2.1 什么是RestTemplate

2.2 配置RestTemplate

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(){
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        //解决401报错时,报java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode
        requestFactory.setOutputStreaming(false);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        restTemplate.setErrorHandler(new RtErrorHandler());
        return restTemplate;
    }
    
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);
        factory.setConnectTimeout(15000);
        return factory;
    }

2.2 RestTemplate 添加请求头headers和请求体body

        HttpHeaders header = new HttpHeaders();
        header.add("X-Consumer-Third-User-Id", "X-Consumer-Third-User-Id");
        header.add("X-Consumer-Third-User-Name", "X-Consumer-Third-User-Name");
        header.set("Authorization", "authorization");
        HttpEntity<AssetProcessVo> httpEntity = new HttpEntity<>(assetProcessVo, header);

2.3 示例代码

/**
     * 远程调用登录接口
     */
    public void accessLoginUrl(){
        HttpHeaders header = new HttpHeaders();
        header.add("X-Consumer-Third-User-Id", "X-Consumer-Third-User-Id");
        header.add("X-Consumer-Third-User-Name", "X-Consumer-Third-User-Name");
        header.set("Authorization", "authorization");
        HttpEntity<AssetProcessVo> httpEntity = new HttpEntity<>(assetProcessVo, header);
        ResponseEntity<ByteArrayOutputStream> exchange;
        try {
            //保存案件名称后,启动工作流
            exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, ByteArrayOutputStream.class);
            if (exchange.getStatusCodeValue() == 200) {
                String response = byteArrayOutputStream.toString();
                ObjectMapper objectMapper = new ObjectMapper();
                RespBean respBean = objectMapper.readValue(response, RespBean.class);
            }
        } catch (RestClientException e) {
            e.printStackTrace();
        }

三:HttpClient

3.1 导入依赖

	<dependency>
	    <groupId>org.apache.httpcomponents</groupId>
	    <artifactId>httpclient</artifactId>
	    <version>4.5.3</version>
	</dependency>

3.2 使用方法

1,创建HttpClient对象;
2,指定请求URL,并创建请求对象,如果是get请求则创建HttpGet对象,post则创建HttpPost对象;
3,如果请求带有参数,对于get请求可直接在URL中加上参数请求,或者使用setParam(HetpParams params)方法设置参数,对于HttpPost请求,可使用setParam(HetpParams params)方法或者调用setEntity(HttpEntity entity)方法设置参数;
4,调用httpClient的execute(HttpUriRequest request)执行请求,返回结果是一个response对象;
5,通过response的getHeaders(String name)或getAllHeaders()可获得请求头部信息,getEntity()方法获取HttpEntity对象,该对象包装了服务器的响应内容。

3.3 代码实现

package com.cnzz.demo.remote.rpc;
 
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;
 
/**
 * ************************************************************
 * Copyright © 2020 cnzz Inc.All rights reserved.  *    **
 * ************************************************************
 *
 * @program: demo
 * @description:
 * @author: cnzz
 * @create: 2020-12-23 17:41
 **/
 
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=telPhone", "GBK"));
        System.out.println("-----------分割线------------");
        System.out.println("-----------分割线------------");
        System.out.println("-----------分割线------------");
 
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("commentId", "telPhone");
        System.out.println(doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", jsonObject));
    }
}

总结 

到此这篇关于java远程调用接口、URL的文章就介绍到这了,更多相关java远程调用接口URL内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文