JAVA调用API

Java调用API很简单,主要分为三步:①找到要调用的API接口②向指定URL添加参数发送请求③对返回的字符串进行处理

以易源数据上接口为例
https://www.showapi.com/ (网址)

话不多说,直接上代码

package Demo;
import java.io.BufferedReader;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;
import java.io.UnsupportedEncodingException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;

public class API {

    public static void main(String[] args) {

        System.out.println(result("9787208061644"));//测试数据
    }

    public static String get_time() {//设置时间
        Date d = new Date();//创建日期对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");//创建格式化日期
        String s = sdf.format(d);//创建成字符串
//        System.out.println(s);
        return s;
    }
//    "http://route.showapi.com/1626-1?"
//    + "showapi_appid%3Dmyappid%26"
//    + "isbn%3D9787208061644%26"
//    + "showapi_sign%3Dmysecret"
    public static String result(String ISBN) {
    	//接口地址
        String requestUrl = "http://route.showapi.com/1626-1";
        //params用于存储请求数据的参数
        Map params = new HashMap();
        //请求数据
        params.put("isbn", ISBN);
        //showapi_appid的值
        params.put("showapi_appid", "94112");
        //添加时间
        params.put("showapi_timestamp", get_time());
        //数字签名,###填你的数字签名,可以在你的个人中心看到
        params.put("showapi_sign", "9a147a4260a34c9c8c4b304decf73744");
        
        //调用httpRequest方法,这个方法主要用于请求地址,并加上请求参数
        String s = httpRequest(requestUrl, params);
       // System.out.println(s);
        return s;
    }

    private static String httpRequest(String requestUrl, Map params) {
    	//buffer用于接受返回的json数据
        StringBuffer buffer = new StringBuffer();
        try {
        	//建立URL,把请求地址给补全,其中urlencode()方法用于把params里的参数给取出来
            URL url = new URL(requestUrl+"?"+urlencode(params)); 
            //打开http连接
            HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();//连接
            httpUrlConnection.setDoInput(true);
            httpUrlConnection.setRequestMethod("GET");
            httpUrlConnection.connect();

            //获得输入
            InputStream inputStream = httpUrlConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");//编码
            BufferedReader bufferedReader =  new BufferedReader(inputStreamReader);


            //将bufferReader的值给放到str里
            String str = null;
            while((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }


            //关闭bufferReader和输入流
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
           // inputStream = null;

            //断开连接
            httpUrlConnection.disconnect();

        } catch(Exception ex) {
            ex.printStackTrace();
        }
        //返回字符串
        return buffer.toString();
    }

    public static String urlencode(Map<String, Object>data) {

    	//将map里的参数变成像 showapi_appid=###&showapi_sign=###&的样子
        StringBuilder sb = new StringBuilder();
        for(Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }
        }
        return sb.toString();
    }
}

你可能感兴趣的:(JAVA调用API)