1. 程式人生 > >java後臺api間的相互呼叫

java後臺api間的相互呼叫

使用springboot寫公司的專案,但是沒有使用springcloud進行開發,有時候需要呼叫其他的java後臺api進行資料獲取,發現了很多問題,最後除錯完畢,記錄下,訪問方式包含get與post,post訪問時需要確定接收的控制層是以實體型別接收還是以欄位型別接收,然後再params這個map中放入鍵值對資料,
map.put("paramType", "entity");放入這個鍵值對錶示對方使用實體型別接收,如果不放入這個鍵值對,就是使用欄位型別接收資料下面上程式碼
package com.xzst.ewms.util;


import net.sf.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by RAZR on 2017/9/18.
 * post傳送資料需要兩種形式,如果接收的controller層使用實體接收,就需要進行以json格式傳送,
 * 如果以單獨欄位進行接收,就需要進行鍵值對的形式傳送
 */
public class ForwardRequest {

    private static final String DEF_CHATSET = "UTF-8";
    private static final int DEF_CONN_TIMEOUT = 60000;
    private static final int DEF_READ_TIMEOUT = 60000;
    private static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";

    /**
     *
     * @param strUrl  訪問地址路徑url
     * @param params  提交的引數map集合
     * @param method  訪問方式GET或者POST
     * @param token   許可權驗證,如果沒有選擇空即可
     * @return
     * @throws Exception
     */
    public static String net(String strUrl, Map params, String method,String token) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if (method == null || method.equals("GET")) {
                strUrl = strUrl + "?" + urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            } else {
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                if ("entity".equals(params.get("paramType"))) {
                    conn.setRequestProperty("Content-Type","application/json");
                } else {
                    conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                }
                conn.setRequestProperty("Content-Length","content.length");

            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setRequestProperty("Authorization",token);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params != null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    if ("entity".equals(params.get("paramType"))) {
                        //如果接收引數為實體型別,就進行json轉碼然後傳送
                        out.writeBytes(GsonTool.toJson(params));
                    } else {
                        //如果接收的引數為幾個欄位型別,就是用鍵值對的形式進行urlencode進行編碼傳送
                        out.writeBytes(urlencode(params));
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }

    //將map型轉為請求引數型(get訪問時使用)
    public static String urlencode(Map<String, Object> data) {
        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 e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
    public  static  String getPhoto64(String photoObjectInfo,String idCard){
        JSONObject object = new JSONObject();
        try {
            object=JSONObject.fromObject(photoObjectInfo);
            if(object.getInt("code")==0){
                if (object.getJSONObject("obj").getJSONObject(idCard).size()!=0) {
                    String res = object.getJSONObject("obj").getJSONObject(idCard).getString("url");
                    return res;
                }
                else return null;
        }
            else {
                return null;}
        }
        catch (Exception e) {
                e.printStackTrace();
                return null;
            }

        }
public  static void main(String[] ags) throws Exception {
    Map map = new HashMap();
    map.put("kewWord", "440301198905147219");
    map.put("tableId", "11");

    System.out.println(net("http://10.4.106.24:8080/relation-web/visual/getFamilyRelationList",map,"POST","Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMTAwMDAwMDAwMDE0OSIsImNyZWF0ZWQiOjE1MTAxOTUxMDk0ODIsImV4cCI6MTUxMDc5OTkwOX0.A7k7FVpbFc56RA6y_l3m3hDDmMseL6nct2jW79Q9YIrsG1CeiRV3opAw7iRVPx9JziALA4Rg9PTByN-NbU-Zeg"));
}

}