当前位置: 代码网 > it编程>编程语言>Java > Java如何实现调用外部Api

Java如何实现调用外部Api

2024年05月26日 Java 我要评论
java调用外部api在日常开发的时候,经常会遇到需要调用别人的接口的场景。但是每次需要的时候,都需要百度,很麻烦,所以这里总结一下,经常调用的方法。1.含有文件的post请求public stati

java调用外部api

在日常开发的时候,经常会遇到需要调用别人的接口的场景。但是每次需要的时候,都需要百度,很麻烦,所以这里总结一下,经常调用的方法。

1.含有文件的post请求

	public static string requestocrforhttp(string url, map<string, string> requestparams, string filepathandname)
			throws exception {
		string result = null;
		closeablehttpclient httpclient = httpclients.createdefault();
		/** httppost */
		httppost httppost = new httppost(url);
		multipartentity reqentity = new multipartentity(); // 建立多文件实例
		filebody filebody = new filebody(new file(filepathandname));
		reqentity.addpart("pic", filebody);// upload为请求后台的file upload;
		for (string key : requestparams.keyset()) {
			string value = requestparams.get(key);
			reqentity.addpart(key, new stringbody(value, charset.forname("utf-8")));
		}
		httppost.setentity(reqentity); // 设置实体
		/** httpresponse */
		closeablehttpresponse httpresponse = httpclient.execute(httppost);
		try {
			httpentity httpentity = httpresponse.getentity();
			result = entityutils.tostring(httpentity, "utf-8");
			entityutils.consume(httpentity);
		} finally {
			try {
				if (httpresponse != null) {
					httpresponse.close();
				}
			} catch (ioexception e) {
				logger.info("## release resouce error ##" + e);
			}
		}
		return result;
	}

2.单纯的json

	public static string sendhttppost(string url, string jsonbody) throws exception {
		closeablehttpclient httpclient = httpclients.createdefault();
		httppost httppost = new httppost(url);
		httppost.addheader("content-type", "application/json");
		httppost.setentity(new stringentity(jsonbody));
		closeablehttpresponse response = httpclient.execute(httppost);
//		system.out.println(response.getstatusline().getstatuscode() + "\n");
		httpentity entity = response.getentity();
		string responsecontent = entityutils.tostring(entity, "utf-8"); 
//		system.out.println(responsecontent);
		response.close();
		httpclient.close();
		return responsecontent;
	}

3.string参数

	public static string requestocrforhttp(string url, map<string, string> requestparams) throws exception {
		string result = null;
		closeablehttpclient httpclient = httpclients.createdefault();
		/** httppost */
		httppost httppost = new httppost(url);
		list<namevaluepair> params = new arraylist<namevaluepair>();
		iterator<entry<string, string>> it = requestparams.entryset().iterator();
//		system.out.println(params.tostring());
		while (it.hasnext()) {
			entry<string, string> en = it.next();
			string key = en.getkey();
			string value = en.getvalue();
			if (value != null) {
				params.add(new basicnamevaluepair(key, value));
			}
		}
		httppost.setentity(new urlencodedformentity(params, "utf-8"));
		/** httpresponse */
		closeablehttpresponse httpresponse = httpclient.execute(httppost);
		try {
			httpentity httpentity = httpresponse.getentity();
			result = entityutils.tostring(httpentity, "utf-8");
			entityutils.consume(httpentity);
		} finally {
			try {
				if (httpresponse != null) {
					httpresponse.close();
				}
			} catch (ioexception e) {
				logger.info("## release resouce error ##" + e);
			}
		}
		return result;
	}

java对接外部api这个问题

有一个小学妹来问我可以将我其他项目的api接入到我现在的项目中吗?我回答“可以”!

需求提出

那么拿到一个需求首先话不多说先分析这个需求的整体思路!需求上面大概有介绍,这里我更深入化的说明一下。

对接外部api接口就是说我在a项目写了一个接口时我的b项目需要到a这个接口的数据,那么在a项目上线的基础上使用b项目去调用a项目的这个所需的接口,如下图:

其实对接外部api就是这么一个过程,当然我们拿到外部数据后面的操作都是由自己去自由发挥了,比如将读取到的数据来显示在这个项目中去给前端显示。或者存入数据库等等。

解决思路

上面已经理解了调用的的思路,有了思路就好解决,现在很多的外部api接口可以给开发时带来便利,当然,调用的方式可能也会有稍些不同,比如手机号查询归属地、邮箱等等。

像这种的一般都是有官方文档可以给我们,很方便。

但是我们去调用自己的api又不是在一个项目中的那就要想想怎么实现了。

话不多说我就拿我之前写了一个demo中的数据吧,刚好项目还在线上。

编码

package edu.controller;

import com.alibaba.fastjson.jsonarray;
import com.alibaba.fastjson.jsonobject;
import com.aliyun.oss.httpmethod;
import edu.entity.eventvo;
import org.springframework.http.responseentity;
import org.springframework.util.linkedmultivaluemap;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.restcontroller;
import org.springframework.web.client.resttemplate;

import java.util.collections;
import java.util.hashmap;
import java.util.list;
import java.util.map;

/**
 * @author fujii
 * @date 2021-10-11 23:12
 * @version springboot 2.2.2
 * @projectname 调用外部api接口
 */
@restcontroller
public class backendapidemo {

    @getmapping("apilist")
    public map<string,object> getbyapilist(){
        //这里先创建一个map用于返回api格式
        map<string,object> maplist = new hashmap<>();
        //1.我们是要去调用外部api,那么肯定要有一个外部api的地址,这里我是拿我的demo作为数据传输
        string apiurl = "这里直接放入你的api接口即可,我的api就不展示了,请谅解!";
        //2.这里有几种方式,你们去试了过后会发现不只有get,这里因为我们是去获取数据,所以是用get
        httpmethod method = httpmethod.get;
        //用于接口返回的jsonobject()
        linkedmultivaluemap map = new linkedmultivaluemap();
        //json接收数据
        jsonobject  urlmethod = client(apiurl,method,map);
        jsonobject jsonobject = jsonobject.parseobject(urlmethod.tojsonstring());
        jsonarray object = jsonobject.parsearray(jsonobject.get("data").tostring());
        if (jsonobject!=null){
            list<eventvo> list = jsonarray.parsearray(object.tojsonstring(), eventvo.class);
            maplist.put("list",list);
            maplist.put("code",200);
            maplist.put("msg", "获取成功!");

        }else{
            maplist.put("code",500);
            maplist.put("msg", "获取失败!");
            return maplist;
        }
        return maplist;
    }
    
    //注意:因为是测试,所有我所有内容全部写在一个文件内方便展示清晰,正规写法应写在服务层
    private jsonobject client(string url, httpmethod method, linkedmultivaluemap params) {
        resttemplate template = new resttemplate();
        responseentity<jsonobject> response = template.getforentity(url, jsonobject.class);
        return response.getbody();
    }
}

测试

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com