調用HTTP接口

調用工具類

package com.tjsoft.tool;

import java.io.ByteArrayOutputStream;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.util.StreamUtils;

import com.alibaba.fastjson.JSONObject;

public class HttpUtil {
	/** POST請求 */
	public static JSONObject doPost(String url, JSONObject params) {

		JSONObject result = new JSONObject();
		result.put("success", true);
		result.put("data", null);
		result.put("code", 200);
		result.put("msg", null);

		OutputStream out = null;
		DataOutputStream dataOutputStream = null;
		InputStream in = null;
		ByteArrayOutputStream baos = null;
		try {
			URLConnection urlConnection = new URL(url).openConnection();
			HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
			// 設置是否向httpUrlConnection輸出,post請求,參數要放在http正文內,因此需要設爲true,
			// 默認情況下是false;
			httpUrlConnection.setDoOutput(true);
			// 設置是否從httpUrlConnection讀入,默認情況下是true;
			httpUrlConnection.setDoInput(true);
			// 忽略緩存
			httpUrlConnection.setUseCaches(false);
			// 設定請求的方法爲"POST",默認是GET
			httpUrlConnection.setRequestMethod("POST");
			httpUrlConnection.connect();

			// 建立輸入流,向指向的URL傳入參數

			String queryString = "";

			if (params != null) {
				for (Entry<String, Object> entry : params.entrySet()) {
					queryString += entry.getKey() + "=" + URLEncoder.encode(entry.getValue().toString(), "UTF-8") + "&";
				}
			}
			if (queryString.length() > 0) {
				queryString = queryString.substring(0, queryString.length() - 1);
				out = httpUrlConnection.getOutputStream();
				dataOutputStream = new DataOutputStream(out);
				dataOutputStream.writeBytes(queryString);

				dataOutputStream.flush();
				out.flush();
			}
			// 獲得響應狀態
			int responseCode = httpUrlConnection.getResponseCode();
			if (HttpURLConnection.HTTP_OK == responseCode) {
				baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				in = httpUrlConnection.getInputStream();
				while ((len = in.read(buffer)) != -1) {
					baos.write(buffer, 0, len);
					baos.flush();
				}
				result.put("success", true);
				result.put("data", baos.toString("UTF-8"));
				result.put("code", 200);
				result.put("msg", "請求成功");
			} else {
				result.put("success", false);
				result.put("code", responseCode);
				result.put("msg", "請求異常");
			}
		} catch (Exception e) {
			result.put("success", false);
			result.put("code", 500);
			result.put("msg", "請求異常,異常信息:" + e.getClass() + "->" + e.getMessage());
		} finally {
			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
					result.put("success", false);
					result.put("code", 500);
					result.put("msg", "請求異常,異常信息:" + e.getClass() + "->" + e.getMessage());
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					result.put("success", false);
					result.put("code", 500);
					result.put("msg", "請求異常,異常信息:" + e.getClass() + "->" + e.getMessage());
				}
			}
			if (dataOutputStream != null) {
				try {
					dataOutputStream.close();
				} catch (IOException e) {
					result.put("success", false);
					result.put("code", 500);
					result.put("msg", "請求異常,異常信息:" + e.getClass() + "->" + e.getMessage());
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					result.put("success", false);
					result.put("code", 500);
					result.put("msg", "請求異常,異常信息:" + e.getClass() + "->" + e.getMessage());
				}
			}
		}
		return result;
	}

	/** GET請求 */
	public static JSONObject doGet(String url, JSONObject params) {

		JSONObject result = new JSONObject();
		result.put("success", true);
		result.put("data", null);
		result.put("code", 200);
		result.put("msg", null);
 
		InputStream in = null;
		ByteArrayOutputStream baos = null;
 
		try {
			// URL傳入參數
			String queryString = "";
 
			if (params != null) {
				for (Entry<String, Object> entry : params.entrySet()) {
					queryString += entry.getKey()
							+ "="
							+ URLEncoder.encode(entry.getValue().toString(),
									"UTF-8") + "&";
				}
			}
 
			if (queryString.length() > 0) {
				queryString = queryString
						.substring(0, queryString.length() - 1);
 
				url = url + "?" + queryString;
			}
 
			URLConnection urlConnection = new URL(url).openConnection();
			HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
			// 設置是否向httpUrlConnection輸出,post請求,參數要放在http正文內,因此需要設爲true,
			// 默認情況下是false;
			httpUrlConnection.setDoOutput(false);
			// 設置是否從httpUrlConnection讀入,默認情況下是true;
			httpUrlConnection.setDoInput(true);
			// 忽略緩存
			httpUrlConnection.setUseCaches(false);
			// 設定請求的方法爲"POST",默認是GET
			httpUrlConnection.setRequestMethod("GET");
			httpUrlConnection.connect();
 
			// 獲得響應狀態
			int responseCode = httpUrlConnection.getResponseCode();
 
			if (HttpURLConnection.HTTP_OK == responseCode) {
				baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				in = httpUrlConnection.getInputStream();
				while ((len = in.read(buffer)) != -1) {
					baos.write(buffer, 0, len);
					baos.flush();
				}
 
				result.put("success", true);
				result.put("data", baos.toString("UTF-8"));
				result.put("code", 200);
				result.put("msg", "請求成功");
			} else {
				result.put("success", false);
				result.put("code", responseCode);
				result.put("msg", "請求異常");
			}
		} catch (Exception e) {
			result.put("success", false);
			result.put("code", 500);
			result.put("msg",
					"請求異常,異常信息:" + e.getClass() + "->" + e.getMessage());
		} finally {
			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
					result.put("success", false);
					result.put("code", 500);
					result.put("msg",
							"請求異常,異常信息:" + e.getClass() + "->" + e.getMessage());
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					result.put("success", false);
					result.put("code", 500);
					result.put("msg",
							"請求異常,異常信息:" + e.getClass() + "->" + e.getMessage());
				}
			}
		}
		return result;
	}
	/*public static void main(String[] args) {
		String url = "http://tyff.test.ngrok.xiaomiqiu.cn/services/businessData/listener/wuhansmzj";
		JSONObject object = doPost(url, null);
		System.out.println(object.toJSONString());
	}*/
	public static String sendHttpRequest(String httpURL,Map<String,String> params) throws Exception{
        //建立URL連接對象
        URL url = new URL(httpURL);
        //創建連接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //設置請求的方式(需要是大寫的)
        conn.setRequestMethod("GET");
        //設置需要輸出
        conn.setDoOutput(true);
        //判斷是否有參數.
        if(params!=null&&params.size()>0){
            StringBuilder sb = new StringBuilder();
            for(Entry<String,String> entry:params.entrySet()){
                sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
            }
            //sb.substring(1)去除最前面的&
            conn.getOutputStream().write(sb.substring(1).toString().getBytes("utf-8"));
        }
        //發送請求到服務器
        conn.connect();
        //獲取遠程響應的內容.
        String responseContent = StreamUtils.copyToString(conn.getInputStream(),Charset.forName("utf-8"));
        conn.disconnect();
        return responseContent;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章