栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java连接第三方接口获取数据

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java连接第三方接口获取数据

第一步

pom文件添加如下依赖


        
            commons-httpclient
            commons-httpclient
            3.1
        

        
        
            com.alibaba
            fastjson
            1.2.32
        

第二步:代码实现 GET请求
public static String doGet(String url, String charset, String token) {
        //1.生成HttpClient对象并设置参数
        HttpClient httpClient = new HttpClient();
        //设置Http连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
        //2.生成GetMethod对象并设置参数
        GetMethod getMethod = new GetMethod(url);
        //设置get请求超时为5秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 30000);
        //设置请求重试处理,用的是默认的重试处理:请求三次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        if (!token.equals("")) {
            postMethod.addRequestHeader("Authorization", token);
        }
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请求
 
    public static String doPost(String url, String jsonstr,String token) {
        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");
if (!token.equals("")) {
            postMethod.addRequestHeader("Authorization", token);
        }
RequestEntity requestEntity = new StringRequestEntity(jsonstr);
        postMethod.setRequestEntity(requestEntity);
        String res = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            System.out.println(code);
            if (code == 200) {
                res = postMethod.getResponseBodyAsString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }
第三步:使用

获得下列接口的数据

http://10.220.4.47:21823/api/UCenter/Login

请求方式post请求

入参
 public class LoginModel
    {
        //用户名
        public string UserName { get; set; }
        //密码
        public string Password { get; set; }
        //系统ID
        public string APPID { get; set; }

返回值类型
略。。。。。。。。。。。
根据对应的返回值类型创建实体类

创建入参实体类

@Data
public class LoginModel {
    @JsonProperty("UserName")     //保持和入参类型一致
    private String UserName;           //保持和传值一致(前端的传值)
    @JsonProperty("Password")
    private String Password;
    @JsonProperty("AppId")
    private String appId;
    @JsonProperty("UserId")
    private String userId;
}

实现接口

String Login(LoginModel model);

实现方法:

public String Login(LoginModel model) {
        try {
           //请求路径
            String loginUrl = "http://10.220.4.47:21823/api/UCenter/Login"
            String jsonStr = JSONObject.toJSON(model).toString();
            String result = doPost(loginUrl, jsonStr, "");
            if (result == "") {
                return "调用远程登录接口失败"
            } else {
                return result;
            }
        } catch (Exception e) {
            return e.getMessage();
        }
    }

请求接口

@PostMapping("/login")
    public String Logon(@RequestBody LoginModel loginModel) {
        if (loginModel != null) {
            //获得第三方接口传来的数据
            return responseModel = commonService.Login(loginModel);
        } else {
            return "参数为空";
        }
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/859548.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号