Java常用的HTTP请求方式

第一种:jdk中自带的URLConnection

示例代码如下:

// An highlighted block
public synchronized static String URLConnectionPost(String url, Map<String, String> header,
			Map<String, String> params, String body) throws ConnectException {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			if (header != null && !header.isEmpty()) {
				Set<String> headers = header.keySet();
				for (String key : headers) {
					conn.setRequestProperty(key, header.get(key));
				}
			}

			if ((params != null && !params.isEmpty()) && (StringUtils.isNotEmpty(body))) {
				System.out.println("传入参数异常,data 和 body 不能同时传入");
				throw new java.net.ConnectException("传入参数异常,data 和 body 不能同时传入");
			}
			/**
			 * 参数
			 */
			StringBuffer p = new StringBuffer();
			if (params != null && !params.isEmpty()) {
				Set<String> param = params.keySet();
				for (String k : param) {
					p.append(k + "=" + params.get(k) + "&");
				}
			}

			if (StringUtils.isNotEmpty(body)) {
				p.append(body);
			}

			if (p.length() > 0) {
				p = p.deleteCharAt(p.length() - 1);
			}

			// 发送POST请求必须设置如下两行
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(p.toString());
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常!" + e);
			throw new java.net.ConnectException("请求错误,status code is[" + result + "]");
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}

		}
		return result;
	}

第二种:apache的httpclient

示例代码如下:

// An highlighted block
public synchronized static byte[] CustomPostMethodPost(String url, String charset, Map<String, String> header,
			Map<String, String> data, String body) throws Exception {
		byte[] result = null;
		CustomPostMethod postMethod = new CustomPostMethod(url);
		try {
			HttpClient client = getClient(charset);

			if (header != null && !header.isEmpty()) {
				Set<String> headers = header.keySet();
				for (String key : headers) {
					postMethod.setRequestHeader(key, header.get(key));
				}
			}
			if (data != null && !data.isEmpty()) {
				Set<String> keys = data.keySet();
				NameValuePair[] ps = new NameValuePair[keys.size()];
				int index = 0;
				for (String k : keys) {
					ps[index++] = new NameValuePair(k, data.get(k));
				}
				postMethod.setRequestBody(ps);
			}
			postMethod.setQueryString(body);

			int statusCode = client.executeMethod(postMethod);

			Header[] _map = postMethod.getResponseHeaders();

			Map<String, String> map = new HashMap<String, String>();
			for (Header h : _map) {
				map.put(h.getName(), h.getValue());
			}
			if (statusCode == 200) {
				result = postMethod.getResponseBody();
				return result;
			} else if (statusCode == 302) {
				result = postMethod.getResponseBody();
				return result;
			}
			postMethod.abort();
			throw new java.net.ConnectException("请求错误,status code is[" + statusCode + "]");
		} catch (Exception e) {
			postMethod.abort();
			throw e;
		} finally {
			postMethod.releaseConnection();
		}
	}


	private static HttpClient getClient(String charset) {
		HttpClient client = new HttpClient(connectionManager);
		HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
		params.setConnectionTimeout(30000);
		params.setSoTimeout(30000);
		params.setDefaultMaxConnectionsPerHost(500);
		params.setMaxTotalConnections(1500);
		params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		HttpClientParams hcp = client.getParams();
		hcp.setParameter("http.connection.timeout", 20 * 1000L);
		hcp.setParameter("http.connection-manager.timeout", 20 * 1000L);
		hcp.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
		hcp.setAuthenticationPreemptive(true);
		return client;
	}


public class CustomPostMethod extends
org.apache.commons.httpclient.methods.PostMethod{
	
	public CustomPostMethod(String url){
		super(url);
	}
	
	public String getResponseBodyAsString() throws IOException {

		GZIPInputStream gzin;

		if (getResponseBody() != null || getResponseStream() != null) {

			if (getResponseHeader("Content-Encoding") != null

					&& getResponseHeader("Content-Encoding").getValue()
							.toLowerCase().indexOf("gzip") > -1) {

				// For GZip response

				InputStream is = getResponseBodyAsStream();

				gzin = new GZIPInputStream(is);

				InputStreamReader isr = new InputStreamReader(gzin,
						getResponseCharSet());

				java.io.BufferedReader br = new java.io.BufferedReader(isr);

				StringBuffer sb = new StringBuffer();

				String tempbf;

				while ((tempbf = br.readLine()) != null) {
					sb.append(tempbf);
					sb.append("\r\n");
				}
				isr.close();
				gzin.close();
				return sb.toString();
			} else {
				// For deflate response
				return super.getResponseBodyAsString();
			}
		} else {

			return null;

		}
	}

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值