http网络请求(java)

48 篇文章 0 订阅

网络请求调用接口,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;
	}
}

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值