Http 请求

一、Http请求

 public static String httpRequestSend(String partUrl, JSONObject params) throws Exception{    	
    	  String zyUrl = getZyUrl(partUrl);
    	  params.put("accessToken", accessToken);
    	  Date date = new Date(System.currentTimeMillis());
    	  SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    	  String timeStamp = sdf.format(date);//请求接口时,请求方当前时间毫
    	  params.put("timeStamp", timeStamp);    	
	  HashMap<String,String> map = new HashMap<String,String>();
	  map.put("Content-Type", "application/json");	
	  String dataResult= HttpRequestProxy.send(zyUrl, params.toString(), map, "utf-8");		
	  return dataResult;
	}

一、HttpRequestProxy.send()

	/**
	 * @param requestUrl
	 * @param content
	 * @param requestProperties
	 * @param charset "utf-8"
	 * @return
	 * @throws Exception
	 */
	public static String send(String requestUrl, String content, HashMap<String, String> requestProperties,
			String charset) throws Exception {
		URL url = new URL(requestUrl);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("POST");

		if (requestProperties != null) {
			for (String key : requestProperties.keySet()) {
				String keyValue = requestProperties.get(key);
				connection.setRequestProperty(key, keyValue);

				if ("ConnectTimeOut".equalsIgnoreCase(key)) {
					connection.setConnectTimeout(Integer.parseInt(keyValue));
				} else if ("ReadTimeOut".equalsIgnoreCase(key)) {
					connection.setReadTimeout(Integer.parseInt(keyValue));
				}
			}
		}

		OutputStream outStream = connection.getOutputStream();
		OutputStreamWriter osw = new OutputStreamWriter(outStream, java.nio.charset.Charset.forName(charset));
		String response = null;

		try {
			try {
				osw.write(content);
			} finally {
				osw.close();
				outStream.close();
			}

			InputStream inStream = null;
			InputStreamReader inStreamReader = null;

			try {
				inStream = connection.getInputStream();
			} catch (Exception exception) {
				inStream = connection.getErrorStream();
				if (inStream == null) {
					throw exception;
				}
			}

			try {
				inStreamReader = new InputStreamReader(inStream, java.nio.charset.Charset.forName(charset));
			} catch (Exception readEx) {
				inStream.close();
				throw readEx;
			}

			StringWriter sw = new StringWriter();
			char[] buf = new char[8096];
			int size = 0;

			try {
				while ((size = inStreamReader.read(buf)) != -1)
					sw.write(buf, 0, size);

				response = sw.toString();
			} finally {
				sw.close();
				inStreamReader.close();
				inStream.close();
			}
		} finally {
			connection.disconnect();
		}

		return response;
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值