java程序发送HTTP请求

java 程序如何发送HTTP请求呢?

有两种实现方式:

1,HttpURLConnection

2,HttpClient

依赖jar包:

 

 

Object[] resultArr = HttpSocketUtil.httpRequest(url, ssl22,
						forcePost22, json_request, contentType,
						session, headerMap, false, null, newEncoding,
						15000, 25000);
				if(ValueWidget.isNullOrEmpty(resultArr)){
					GUIUtil23.errorDialog("404");
					return;
				}
				byte[] resultJsonBytes = (byte[])resultArr[0];
				if (ValueWidget.isNullOrEmpty(resultJsonBytes)) {
					resultTA.setText("请检查请求的url 是否正确(" + url + ")");
					GUIUtil23.warningDialog("返回结果为空.");
					return;
				}
				String resultJson = new String(resultJsonBytes,
						SystemHWUtil.CHARSET_GBK);
				String resultJson2 = new String(resultJsonBytes,
						SystemHWUtil.CHARSET_UTF);

				// 把http请求结果(json字符串)转化为map
				Map<String, Object> resultMap = null;
				// if(!"{}".equals(resultJson2.replaceAll(" ", ""))){//"{}"
				resultMap = JsonUtils.getMap(resultJson2);// }
				// System.out.println(resultMap);
				// 判断该接口是否是启动接口,因为启动接口会返回token
				if (!ValueWidget.isNullOrEmpty(resultMap)
						&& resultMap.containsKey(token_label)) {
					addInputBox(token_label, (String)resultMap.get(token_label));
				}else{//server not offer token
					
				}
				// String sessionID = caseDetail.getSessionId();
				// if (!ValueWidget.isNullOrEmpty(sessionID)) {
				// addInputBox( sessionId_label, sessionID);
				// }
				if (!ValueWidget.isNullOrEmpty(resultArr[1])) {
					session = (String)resultArr[1];
				}
				if (!ValueWidget.isNullOrEmpty(session)) {
					sessionTF.setText(session);
				}

 

httpRequest的返回值是一个数组:

返回数组有4个元素,分别是:

1,request result(byte[]):应答体

2,sessionId

3,contentType:应答的content type;

4,response code:HTTP 状态码

httpRequest 的实现如下:

/***
	 * 
	 * @param urlStr
	 * @param ssl
	 * @param forcePost
	 * @param sendData
	 * @param contentType
	 * @param cookie
	 * @param headers
	 * @param isWrite2file
	 * @param destFile
	 * @param charset
	 * @param connectTimeout
	 * @param readTimeout
	 * @return : request result(byte[]) ;sessionId;contentType;response code
	 * @throws Exception
	 */
	public static Object[] httpRequest(String urlStr, boolean ssl,
			boolean forcePost, String sendData, String contentType,
			String cookie, Map<String, String> headers, boolean isWrite2file,
			Object destFile, String charset, int connectTimeout, int readTimeout)
			throws Exception {
		return httpRequest(urlStr, ssl, forcePost, sendData, contentType,
				cookie, headers, isWrite2file, destFile, charset,
				connectTimeout, readTimeout, null);
	}

/***
	 * 
	 * @param urlStr
	 * @param sendData
	 * @param contentType
	 *            : default is application/x-www-form-urlencoded
	 * @param cookie
	 * @param headers
	 *            : request header
	 * @param isWrite2file
	 *            : whether write to file
	 * @param destFile
	 *            file which will be written
	 * @return : request result(byte[]) ;sessionId;contentType;response code
	 * @throws Exception
	 */
	public static Object[] httpRequest(String urlStr, boolean ssl,
			boolean forcePost, String sendData, String contentType,
			String cookie, Map<String, String> headers, boolean isWrite2file,
			Object destFile, String charset, int connectTimeout,
			int readTimeout, String sizeHeadKey) throws Exception {
		// URL url = new URL(urlString);
		if (isDetail)
			System.out.println("ssl:" + ssl);
		HttpURLConnection huc = beforeConnect(urlStr, ssl, forcePost, sendData,
				contentType, cookie, headers, charset, connectTimeout,
				readTimeout);

		File writeFile = null;
		if (destFile instanceof File) {
			writeFile = (File) destFile;
		} else {
			if (!ValueWidget.isNullOrEmpty(destFile)) {
				writeFile = new File((String) destFile);
			}
		}
		if (isDetail)
			System.out.println("writeFile:" + writeFile);
		//应答码,返回码
		int resCode = huc.getResponseCode();
		byte[] result = connection(resCode,huc, isWrite2file, writeFile, sizeHeadKey);
		if (!isWrite2file && (result == null)) {
			System.out
					.println("[HttpSocketUtil.httpRequest]connection return is null.");
			return null;
		}
		if (!ValueWidget.isNullOrEmpty(result)) {
			System.out.println("read result length of bytes:" + result.length);
		}
		Object[] retArr = new Object[3];
		String session_value = huc
				.getHeaderField(SystemHWUtil.KEY_HEADER_COOLIE);
		// Map<String, List<String>> responseHeaders = huc.getHeaderFields();
		// for (Iterator<?> it = responseHeaders.keySet().iterator();
		// it.hasNext();) {
		// System.out.println("key:" + it.next());
		// }
		if (ValueWidget.isHasValue(session_value)) {
			String[] sessionId = session_value.split(";");
			retArr[1] = sessionId[0];
			if (isDetail) {
				System.out
						.println("[HttpSocketUtil.httpRequest]session id is :"
								+ sessionId[0]);
			}
		}
		retArr[2] = huc.getContentType();
		retArr[3] = resCode;
		retArr[0] = result;
		// if (isWrite2file && destFile != null) {
		// byte[] bytes = (byte[]) result;
		//
		// FileUtils.writeBytesToFile(bytes, writeFile);
		// }
		return retArr;
	}

源码见:com.http.util.HttpSocketUtil 

下载地址:http://pan.baidu.com/s/1hqeXBhE

 

你可能感兴趣的:(java,发送http,java访问http接口)