http網絡請求(java)

網絡請求調用接口,HttpTool.Request();


package sc.tool.http;

import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.concurrent.Executors;

import org.json.JSONObject;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;


/** 
 * HttpTool.java: 網絡請求函數工具類(支持POST、GET,以及JSON參數請求)。
 * 
 * 使用用法:HttpTool.Request();
 * 
 * ----- scimence 2020-04-02 下午18:13:35 
 **/
public class HttpTool
{
	public static void Example()
	{
		// https://www.baidu.com/s?tn=baidu&wd=http請求 scimence
			
		String httpUrl = "https://www.baidu.com/s";
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("tn", "baidu");
		params.put("wd", "http請求 scimence");
		
		CallBackS call = new CallBackS()
		{
			@Override
			public void F(String data)
			{
				System.out.println("網絡請求返回信息 -> \r\n" + data);
			}
		};
		
		HttpTool.Request(httpUrl, params, RequestMethod.GET, call);
	}
	
	/** 定義兩種Http請求類型 */
	public static enum RequestMethod
	{
		POST, GET;
		
		/** 轉化爲字符串形式,此枚舉中可獲取到 "POST"、"GET" */
		public String toString()
		{
			return this.name();
		}
		
	}
	
	/** 回調處理接口類,返回字符串數據 */
	public interface CallBackS
	{
		/** 回調處理邏輯,返回字符串數據 */
		public void F(String data);
	}
	
	//------------------------------------------------
	
	/** http請求,是否輸出相關log信息 */
	public static boolean	showRequestLog	= true;
	private static String	TAG				= "HttpTool.java";
	
	/** http請求的編碼格式 UTF-8、GBK 等 */
	public static String	CHARSET			= "UTF-8";
	
	/** http連接超時時間,默認不設置 */
	public static int connectTimeout = 0;
	
	/** http讀取超時時間,默認不設置 */
	public static int readTimeout = 0;
	
	
	/** Map參數轉化爲字符串,進行網絡請求 */
	public static void Request(String httpUrl, HashMap<String, String> map, RequestMethod method, CallBackS call)
	{
		if (showRequestLog) Log.d(TAG, "網絡請求參數 ->> " + httpUrl + "?" + map.toString());
		String data = ToString(map);
		Request(httpUrl, data, method, call);
	}
	
	/** Map參數轉化爲JSON字符串,進行網絡請求 */
	public static void RequestJson(String httpUrl, HashMap<String, String> map, RequestMethod method, CallBackS call)
	{
		if (showRequestLog) Log.d(TAG, "網絡請求參數 ->> " + httpUrl + "?" + map.toString());
		String data = ToJsonString(map);
		Request(httpUrl, data, method, call);
	}
	
	/** 網絡請求接口,通用方法 */
	public static void Request(final String httpUrl, final String data, final RequestMethod method, final CallBackS call)
	{
		// 在子線程執行網絡請求,在主線程執行回調處理邏輯
		Executors.newCachedThreadPool().execute(new Runnable()
		{
			@Override
			public void run()
			{
				try
				{
					if (showRequestLog) Log.d(TAG, "執行網絡請求 ->> " + httpUrl + "?" + data);
					
					String result = RequestNonMainThread(httpUrl, data, method);
					
					if (showRequestLog) Log.d(TAG, "網絡請求返回 ->> " + result);
					
					MainThreadRunF(result);	// 返回網絡請求獲取到的數據
				}
				catch (Exception ex)
				{
					ex.printStackTrace();
					Log.e(TAG, "Request函數,網絡請求異常 ->> " + ex.toString());
					
					MainThreadRunF("");
				}
			}
			
			/** 在主線程中執行回調處理邏輯 */
			private void MainThreadRunF(final String data)
			{
				if (call != null)
				{
					new Handler(Looper.getMainLooper()).post(new Runnable()
					{
						@Override
						public void run()
						{
							call.F(data);	// 返回網絡請求獲取到的數據
						}
					});
				}
			}
		});
	}
	
	/** 網絡連接、請求處理函數。此函數必須在非主線程中調用。(外部一般不直接調用該函數) */
	public static String RequestNonMainThread(String httpUrl, String data, RequestMethod method)
	{
		try
		{
			if (data == null) data = "";
			if (method == RequestMethod.GET && !data.equals(""))
			{
				httpUrl += "?" + data;
				data = "";
			}
			
			HttpURLConnection conn = (HttpURLConnection) new URL(httpUrl).openConnection();
			conn.setRequestMethod(method.toString());					// POST或GET
			if(connectTimeout > 0) conn.setConnectTimeout(connectTimeout);
			if(readTimeout > 0) conn.setReadTimeout(readTimeout);
			if (method == RequestMethod.POST) conn.setDoOutput(true);	// post方法,輸出數據
			conn.setDoInput(true);	// 接收數據
			conn.connect();
			
			// 輸出數據
			if (!data.equals(""))
			{
				OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), CHARSET);
				writer.write(data);
				writer.flush();
				writer.close();
			}
			
			// 接收數據
			StringBuffer sb = new StringBuffer();
			if (conn.getResponseCode() == 200)
			{
				InputStreamReader reader = new InputStreamReader(conn.getInputStream(), CHARSET);
				int len;
				char[] buf = new char[1024];
				while ((len = reader.read(buf)) != -1)
				{
					sb.append(buf, 0, len);
				}
				reader.close();
			}
			conn.disconnect();
			return sb.toString();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			Log.e(TAG, "RequestNonMainThread函數異常 -> " + e.toString());
			return "";
		}
	}
	
	/** 將map參數,轉化爲http請求串, 如: token=231fasac&sign=66adbfd */
	public static String ToString(HashMap<String, String> map)
	{
		try
		{
			StringBuffer sb = new StringBuffer();
			if (map != null && !map.isEmpty())
			{
				for (String k : map.keySet())
				{
					if (k != null && !"".equals(k))
					{
						String v = map.get(k);
						if (v == null) v = "null";
						sb.append("&").append(k).append("=").append(URLEncoder.encode(v, CHARSET));
					}
				}
			}
			String tmp = sb.toString();
			return tmp.equals("") ? "" : tmp.substring(1);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			Log.e(TAG, "ToString函數異常 -> " + e.toString());
			return "";
		}
	}
	
	/** 將map參數,轉化爲Json字符串,如:{ "token":"231fasac", "sign": "66adbfd"} */
	public static String ToJsonString(HashMap<String, String> map)
	{
		try
		{
			JSONObject params = new JSONObject();
			if (map != null && !map.isEmpty())
			{
				for (String k : map.keySet())
				{
					if (k != null && !"".equals(k))
					{
						String v = map.get(k);
						if (v == null) v = "null";
						params.put(k, v);
					}
				}
			}
			return params.toString();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			Log.e(TAG, "ToJsonString函數異常 -> " + e.toString());
			return "{}";
		}
	}
	
	//-----------------------------------------------
	
	/** 替換url中的主機域名爲解析獲得的ip */
	public static String getIpUrl(String url)
	{
		String ServerName = getServerName(url);
		String ip = getIP(url);
		if (!ip.equals("")) url = url.replaceFirst(ServerName, ip);
		return url;
	}
	
	// LTSDK_ORDER_URL = "http://www.baidu.com/order/allplat";
	/** 獲取url中的域名信息 */
	public static String getServerName(String url)
	{
		url = url.trim();
		
		if (url.contains("//"))
		{
			int index = url.indexOf("//") + "//".length();
			url = url.substring(index);		// www.baidu.com/order/allplat
		}
		if (url.contains("/"))
		{
			int index = url.indexOf("/");
			url = url.substring(0, index);	// www.baidu.com
		}
		
		return url;
	}
	
	// LTSDK_ORDER_URL = "http://www.baidu.com/order/allplat";
	/** 解析域名爲ip信息 */
	public static String getIP(String url)
	{
		String ip = "";
		
		try
		{
			String ServerName = getServerName(url);
			InetAddress address = InetAddress.getByName(ServerName);
			ip = address.getHostAddress().toString();
			
			if (showRequestLog) Log.d(TAG, " 域名(" + ServerName + ") ->> Ip(" + ip + ")");
		}
		catch (Exception e)
		{
			if (showRequestLog) Log.d(TAG, "網絡異常,域名(" + url + ")無法訪問,解析Ip失敗!");
			Log.e(TAG, "getIP函數異常 -> " + e.toString());
		}
		
		return ip;
	}
}

 

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