1. 程式人生 > >Java 讀取get 和post 介面 工具類整理

Java 讀取get 和post 介面 工具類整理

package cn.ijiami.mamp.manage.util;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.List;

/**
 *
 *<p>類描述:介面讀取工具。</p>
 */
public class ReadUrlUtil {

/***
     * 加密
     * @param s
     * @return
     */
    public static String cjkEncode(String s)
    {
        if (s == null)
            return "";
        StringBuffer stringbuffer = new StringBuffer();
        int i = 0;
        for (int j = s.length(); i < j; i++)
        {
            char c = s.charAt(i);
            if (c >= '\200' || c == '[' || c == ']')
            {
                stringbuffer.append("[");
                stringbuffer.append(Integer.toString(c, 16));
                stringbuffer.append("]");
            } else
            {
                stringbuffer.append(c);
            }
        }

        return stringbuffer.toString();
    }



    public static JSONObject readJsonFromUrl(String url) {
        InputStream is = null;
        try {   url  =cjkEncode(url);
            is = new URL(url).openStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            StringBuilder sb = new StringBuilder();
            int cp;
            while ((cp = rd.read()) != -1) {
                sb.append((char) cp);
            }
            String jsonText = sb.toString();
            JSONObject json = JSONObject.parseObject(jsonText);
            return json;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e1) {
            e1.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return  null;
    }



    /**
     * 向指定 URL 傳送POST方法的請求
     * @param url 傳送請求的 URL
     * @param param 請求引數,請求引數應該是 name1=value1&name2=value2 的形式。
     * @return 所代表遠端資源的響應結果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 開啟和URL之間的連線
            URLConnection conn = realUrl.openConnection();
            // 設定通用的請求屬性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 傳送POST請求必須設定如下兩行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //1.獲取URLConnection物件對應的輸出流
            out = new PrintWriter(conn.getOutputStream());
            //2.中文有亂碼的需要將PrintWriter改為如下
            //out=new OutputStreamWriter(conn.getOutputStream(),"UTF-8")
            // 傳送請求引數

                out.print(param);

            // flush輸出流的緩衝
            out.flush();
            // 定義BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("傳送 POST 請求出現異常!"+e);
            e.printStackTrace();
        }
        //使用finally塊來關閉輸出流、輸入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        System.out.println("post推送結果:"+result);

        return result;
    }


    /**
     * 根據屬性名獲取屬性值
     * */
    public static String getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[] {});
            String value = (String)method.invoke(o, new Object[] {});
            return value;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String url ="http://172.10.3.89:10200/schedule";
      /*  JSONObject jsonObject = readJsonFromUrl(url);
        JSONArray jsonArray = JSONArray.parseArray(jsonObject.get("code")+"");
        //jsonArray.get(1).getClass().
        List<Object> list  = jsonArray.toJavaList(Object.class);*/
      String[] strs = new String[]{};
      // JSONObject str =  sendPost(url,"project_name=channel_spider&spider_name=app_channel&channel_id=40");
      //  System.err.println(str);
    }
}