Java实现调用接口API并返回数据

来自:网络
时间:2024-06-09
阅读:

Java调用接口API并返回数据

Get方法

import com.alibaba.fastjson.JSONObject;
import edu.zhku.fire_ant_project.config.WxConstant;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpCallOtherInterfaceUtils {
    public static void main(String args[]) {
        HttpClient client = HttpClients.createDefault();
        // 要调用的接口方法
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ WxConstant.appid +"&secret="+WxConstant.secret;
        HttpGet httpGet=new HttpGet(url);
        JSONObject jsonObject = null;
        try {
            HttpResponse res = client.execute(httpGet);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 返回json格式:
                jsonObject = JSONObject.parseObject(EntityUtils.toString(res.getEntity()));
                System.out.println(jsonObject);
            }
        } catch (Exception e) {
            System.out.println("服务间接口调用出错!");
            e.printStackTrace();
        }
    }
}

post方法

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpCallOtherInterfaceUtils {
    public static String callOtherInterface(JSONObject jsonParam, String port, String postUrl) {
        HttpClient client = HttpClients.createDefault();
        // 要调用的接口方法
        String url = "http://localhost:" + port + postUrl;
        HttpPost post = new HttpPost(url);
        JSONObject jsonObject = null;
        try {
            StringEntity s = new StringEntity(jsonParam.toString(), "UTF-8");
            //s.setContentEncoding("UTF-8");//此处测试发现不能单独设置字符串实体的编码,否则出错!应该在创建对象时创建
            s.setContentType("application/json");
            post.setEntity(s);
            post.addHeader("content-type", "application/json;charset=UTF-8");
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 返回json格式:
                jsonObject = JSONObject.parseObject(EntityUtils.toString(res.getEntity()));
            }
        } catch (Exception e) {
            System.out.println("服务间接口调用出错!");
            e.printStackTrace();
            //throw new RuntimeException(e);
        }
        return jsonObject.toString();
    }
}

Java跨服务调用接口

Java程序跨服务调用接口,通常可以使用以下方式:

  • RESTful API:通过HTTP协议进行通信,使用RESTful API调用其他服务的接口。
  • RPC:使用远程过程调用(RPC)框架,如Dubbo、gRPC等,通过序列化和反序列化技术实现跨服务调用。
  • 消息队列:使用消息队列,如Kafka、RabbitMQ等,服务之间通过消息队列进行异步通信。
  • HTTP客户端:使用Java内置的HTTP客户端,如HttpURLConnection、Apache HttpClient等,通过HTTP协议调用其他服务的接口。

无论使用哪种方式,都需要了解其他服务的接口定义和调用方式,以及网络通信的安全性和稳定性等方面的考虑。同时,需要注意接口版本的兼容性和错误处理等问题。

这里提供一个使用Java内置的HttpURLConnection进行POST请求的示例代码:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class HttpPostExample {
 
    private static final String POST_URL = "http://engine-server-host:port/api/client/data/push";
    private static final String USER_AGENT = "Mozilla/5.0";
 
    public static void main(String[] args) throws IOException {
        URL obj = new URL(POST_URL);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
 
        // 添加请求头
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
 
        // 设置POST请求体
        String postBody = "your_post_body_here";
        con.setDoOutput(true);
        try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
            wr.writeBytes(postBody);
            wr.flush();
        }
 
        // 发送POST请求并获取响应
        int responseCode = con.getResponseCode();
        System.out.println("POST Response Code :: " + responseCode);
 
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            System.out.println("POST Response :: " + response.toString());
        }
    }
}

在代码中,需要将POST_URL替换为引擎端的API接口地址,将postBody替换为要发送的POST请求体。

需要注意的是,这里的POST请求体需要按照引擎端API接口的要求进行格式化。 

总结

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

返回顶部
顶部