Java如何调用接口API并返回数据

1.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();
        }
    }
}

2. 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,apache,开发语言)