java通過java.net.URL發送http請求調用接口


一般在*.html,*.jsp頁面中我們通過使用ajax調用接口,這個是我們通常用的。對於這些接口,大都是本公司寫的接口供自己調用,所以直接用ajax就可以。但是,如果是多家公司共同開發一個東西,一個功能可能要調多個接口,一兩個ajax可以在jsp頁面上顯示,但是如果多了,就不能寫這么多ajax在前端了。這時候需要封裝一成一個接口,在接口里面如何調用其他接口呢?這就用到了java.net.URL這個類。

java.net.URL用法如下

     BufferedReader in=null;
        java.net.HttpURLConnection conn=null;
        String msg = "";// 保存調用http服務后的響應信息
        try
        {
       //實例化url java.net.URL url
= new java.net.URL(path);
       //根據url獲取HttpURLConnection conn
= (java.net.HttpURLConnection) url.openConnection();
       //設置請求的參數 conn.setRequestMethod(
"POST"); conn.setConnectTimeout(5 * 1000);// 設置連接超時時間為5秒 conn.setReadTimeout(20 * 1000);// 設置讀取超時時間為20秒 conn.setDoOutput(true); // 使用 URL 連接進行輸出,則將 DoOutput標志設置為 true conn.setDoInput(true); conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); //conn.setRequestProperty("Content-Encoding","gzip"); conn.setRequestProperty("Content-Length", String.valueOf(params.length())); //設置請求內容(長度)長度 OutputStream outStream = conn.getOutputStream(); // 返回寫入到此連接的輸出流 outStream.write(params.getBytes()); //將參數寫入流中 outStream.close();//關閉流 if (conn.getResponseCode() == 200) { // HTTP服務端返回的編碼是UTF-8,故必須設置為UTF-8,保持編碼統一,否則會出現中文亂碼 in = new BufferedReader(new InputStreamReader((InputStream) conn.getInputStream(), "UTF-8")); msg = in.readLine(); } }catch(Exception ex) { ex.printStackTrace(); }finally { if(null!=in) { in.close(); } if(null!=conn) { conn.disconnect(); } } return msg;

HttpUtil工具類 

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.net.HttpURLConnection;
import java.net.URL;


/**
 * http工具
 *
 */
public final class HttpUtil {
    /**
     * 模擬http協議發送get請求
     **/
    public static String sendGetRequest(String url) {
        String result = "";
        InputStream in = null;

        HttpURLConnection connection = null;

        try {
            URL httpUrl = new URL(url);
            connection = (HttpURLConnection) httpUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestMethod("GET");
            connection.connect();

            if (connection.getResponseCode() == 200) {
                in = connection.getInputStream();

                ByteArrayOutputStream bs = new ByteArrayOutputStream();
                int n = 0;
                byte[] datas = new byte[2048];

                while ((n = in.read(datas)) != -1) {
                    bs.write(datas, 0, n);
                }

                bs.flush();
                result = new String(bs.toByteArray(), "utf-8");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                connection.disconnect();
            } catch (Exception ex) {
            }
        }

        return result;
    }

    /**
    * 模擬http協議發送post請求
    **/
    public static String sendPostRequest(String url, String param) {
        InputStream in = null;
        String result = "";
        HttpURLConnection connection = null;

        try {
            URL httpUrl = new URL(url);
            connection = (HttpURLConnection) httpUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.getOutputStream().write(param.getBytes("utf-8"));
            connection.getOutputStream().flush();

            if (connection.getResponseCode() == 200) {
                in = connection.getInputStream();

                ByteArrayOutputStream bs = new ByteArrayOutputStream();
                int n = 0;
                byte[] datas = new byte[2048];

                while ((n = in.read(datas)) != -1) {
                    bs.write(datas, 0, n);
                }

                bs.flush();
                result = new String(bs.toByteArray(), "utf-8");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            try {
                connection.disconnect();
            } catch (Exception ex) {
            }
        }

        return result;
    }

    /**
     * 普通post文件上傳
     */
    public static String upLoadAttachment(String url, String fileName, File file) {
        String result = null;

        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL httpUrl = new URL(url);
            connection = (HttpURLConnection) httpUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);

            String bound = "----------" + System.currentTimeMillis();
            connection.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + bound);

            StringBuilder sb = new StringBuilder();
            sb.append("--");
            sb.append(bound);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data;name=\"" + fileName +
                "\";filename=\"" + file.getName() + "\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");

            byte[] data = sb.toString().getBytes("utf-8");
            OutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(data);

            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];

            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }

            in.close();

            byte[] foot = ("\r\n--" + bound + "--\r\n").getBytes("utf-8"); // 定義最后數據分隔線
            out.write(foot);
            out.flush();
            out.close();

            InputStream inn = connection.getInputStream();
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            int n = 0;
            byte[] datas = new byte[2048];

            while ((n = inn.read(datas)) != -1) {
                bs.write(datas, 0, n);
            }

            bs.flush();
            result = new String(bs.toByteArray(), "utf-8");

            return result;
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                connection.disconnect();
            } catch (Exception ex) {
            }
        }

        return null;
    }
    
   /**
     * post文件上傳 - 使用InputStream輸入流(例如MultipartFile從前端獲取文件后轉發給其他的服務器)
     */
    public static String upLoadAttachment(String url,String keyName, String fileName, InputStream fins) {
        String result = null;

        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL httpUrl = new URL(url);
            connection = (HttpURLConnection) httpUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);

            String bound = "----------" + System.currentTimeMillis();
            connection.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + bound);

            StringBuilder sb = new StringBuilder();
            sb.append("--");
            sb.append(bound);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data;name=\"" + keyName +
                    "\";filename=\"" + fileName + "\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");

            byte[] data = sb.toString().getBytes("utf-8");
            OutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(data);

            DataInputStream in = new DataInputStream(fins);
            int bytes = 0;
            byte[] bufferOut = new byte[1024];

            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }

            in.close();

            byte[] foot = ("\r\n--" + bound + "--\r\n").getBytes("utf-8"); // 定義最后數據分隔線
            out.write(foot);
            out.flush();
            out.close();

            InputStream inn = connection.getInputStream();
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            int n = 0;
            byte[] datas = new byte[2048];

            while ((n = inn.read(datas)) != -1) {
                bs.write(datas, 0, n);
            }

            bs.flush();
            result = new String(bs.toByteArray(), "utf-8");

            return result;
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                connection.disconnect();
            } catch (Exception ex) {
            }
        }

        return null;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM