java 发送post/get请求工具类

需要导入jar包 ,用来json解析 

//jar,选择一个就行,主要是用以post发送数据时转json,本工具用的alibaba json。

<!--org json -->
<dependency>
	<groupId>org.codehaus.jackson</groupId>
	<artifactId>jackson-mapper-asl</artifactId>
	<version>1.9.8</version>
	<type>jar</type>
    <scope>compile</scope>
</dependency>

<!--net json -->
<dependency>
	<groupId>net.sf.json-lib</groupId>
	<artifactId>json-lib</artifactId>
	<version>2.4</version>
	<classifier>jdk15</classifier>
</dependency>

<!--alibaba json -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.47</version>
</dependency>

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;


/*
* java post/get请求工具类
*/
public class HttpUtil {
	/**
	 * 发送GET请求
	 * 
	 * @param url
	 *            String
	 * @param parameters
	 *            Map【String, Object】
	 * @return
	 */
	public static String sendGet(String url, Map<String, Object> parameters) {
		String result = "";
		BufferedReader in = null;// 读取响应输入流
		StringBuffer sb = new StringBuffer();// 存储参数
		String params = "";// 编码之后的参数
		try {
			// 编码请求参数
			if (parameters.size() == 1) {
				for (String name : parameters.keySet()) {
					sb.append(name).append("=")
							.append(java.net.URLEncoder.encode(String.valueOf(parameters.get(name)), "UTF-8"));
				}
				params = sb.toString();
			} else {
				for (String name : parameters.keySet()) {
					sb.append(name).append("=")
							.append(java.net.URLEncoder.encode(String.valueOf(parameters.get(name)), "UTF-8"))
							.append("&");
				}
				String temp_params = sb.toString();
				params = temp_params.substring(0, temp_params.length() - 1);
			}
			String full_url = url + "?" + params;
			// System.out.println(full_url);
			// 创建URL对象
			java.net.URL connURL = new java.net.URL(full_url);
			// 打开URL连接
			java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL.openConnection();
			// 设置通用属性
			httpConn.setRequestProperty("Accept", "*/*");
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
			// 建立实际的连接
			httpConn.connect();
			// 响应头部获取
			Map<String, List<String>> headers = httpConn.getHeaderFields();
			// 遍历所有的响应头字段
			// for (String key : headers.keySet()) {
			// System.out.println(key + "\t:\t" + headers.get(key));
			// }
			// 定义BufferedReader输入流来读取URL的响应,并设置编码方式
			in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
			String line;
			// 读取返回的内容
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 发送POST请求
	 * 
	 * @param url
	 *            String
	 * @param map
	 *            Map【String, Object】
	 * @return String
	 */
	public static String sendPost(String url, Map<String, Object> map) {
		// 返回的结果
		StringBuffer result = new StringBuffer();
		// 读取响应输入流
		BufferedReader in = null;
		PrintWriter out = null;
		HttpURLConnection httpConn=null;
		// 处理请求参数
		StringBuffer sb = new StringBuffer();
		// 编码之后的参数
		String params = "";
		try {
			JSONObject json = new JSONObject(map);
			// 编码请求参数
			if (json.size() == 1) {
				for (String name : json.keySet()) {
					sb.append(name).append("=").append(String.valueOf(json.get(name)));
				}
				params = sb.toString();
			} else {
				for (String name : json.keySet()) {
					sb.append(name).append("=").append(String.valueOf(json.get(name))).append("&");
				}
				String temp_params = sb.toString();
				params = temp_params.substring(0, temp_params.length() - 1);
			}
			// 创建URL对象
			URL connURL = new URL(url);
			// 打开URL连接
			httpConn = (HttpURLConnection) connURL.openConnection();
			// 设置通用属性
			httpConn.setRequestMethod("POST");
			httpConn.setConnectTimeout(10000);
			httpConn.setReadTimeout(10000);
			// 设置POST方式
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);

			// httpConn.setRequestProperty("Accept", "*/*");
			// httpConn.setRequestProperty("Connection", "Keep-Alive");
			// httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0;
			// Windows NT 6.1)");
			// httpConn.setRequestProperty("Content-Type",
			// "application/json;charset=UTF-8");

			// 获取HttpURLConnection对象对应的输出流
			out = new PrintWriter(httpConn.getOutputStream());
			// 发送请求参数
			out.write(params);
			// flush输出流的缓冲
			out.flush();

			if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				String line = "";
				in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8"));
				while ((line = in.readLine()) != null) {
					result.append(line);
				}
				in.close();
				return result.toString();
			} else {
				throw new Exception("HTTP_POST_ERROR_RETURN_STATUS:" + httpConn.getResponseCode());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
				httpConn.disconnect();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return null;
	}

	// 发送GET 请求举例
	// ******************************************************************************
	// Map<String,Object> params = new HashMap<String,Object>();
	// params.put("user", "lgg");
	// String result = HttpUtil.sendGet("https://mp.csdn.net/postedit", params);
	// System.out.println("结果是:"+result);
	// ******************************************************************************

	// 发送POST一般请求
	// ******************************************************************************
	// Map<String,Object> params = new HashMap<String,Object>();
	// params.put("user", "lgg");
	// String result = HttpUtil.sendPost("https://mp.csdn.net/postedit", params);
	// System.out.println("结果是:"+result);
	// ******************************************************************************

	// 发送POST的json请求
	// ******************************************************************************
	// User user = new User();
	// user.setName("张三");
	// user.setAge(18);
	// Map<String,Object> params = new HashMap<String,Object>();
	// params.put("queryJson", JSON.toJSONString(user));
	// String result = HttpUtil.sendPost("https://mp.csdn.net/postedit", params);
	// System.out.println("结果是:"+result);
	// ******************************************************************************
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值