Httpclient

<span style="font-size:14px;">import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.toruk.pub.Log;


public class HttpClient {

	/**
	 * 功能:
	 * 
	 * @param postURL
	 * @param requestBody
	 * @param sendCharset
	 * @param readCharset
	 * @return
	 */
	public static String send(String postURL, String requestBody,
			String sendCharset, String readCharset) {

		Log.print(requestBody);

		// Post请求的url,与get不同的是不需要带参数,参数放requestBody中是POST请求,参数拼接在postURL后面是get请求
		HttpURLConnection httpConn = null;

		try {
			Log.print("#############请求URL:############" + postURL);
			URL postUrl = new URL(postURL);
			// 打开连接
			httpConn = (HttpURLConnection) postUrl.openConnection();
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			httpConn.setRequestMethod("POST");
			httpConn.setUseCaches(false);
			httpConn.setInstanceFollowRedirects(true);
			httpConn
					.setRequestProperty("Content-Type",
							"application/x-www-form-urlencoded; charset="
									+ sendCharset);
			httpConn.setConnectTimeout(1000 * 300);
			httpConn.setReadTimeout(1000 * 300);
			// 连接,从postUrl.openConnection()至此的配置必须要在 connect之前完成,
			// 要注意的是connection.getOutputStream会隐含的进行 connect。
			httpConn.connect();
			DataOutputStream out = new DataOutputStream(httpConn
					.getOutputStream());
			out.write(requestBody.getBytes(sendCharset));
			out.flush();
			out.close();
			int status = httpConn.getResponseCode();
			if (status != HttpURLConnection.HTTP_OK) {
				Log.print("发送请求失败,状态码:[" + status + "] 返回信息:"
						+ httpConn.getResponseMessage());
				return null;
			}
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					httpConn.getInputStream(), readCharset));
			StringBuffer responseSb = new StringBuffer();
			String line = null;
			while ((line = reader.readLine()) != null) {
				responseSb.append(line.trim());
			}
			reader.close();
			Log.print("##############请求返回值:#############");
			Log.print(responseSb);
			return responseSb.toString().trim();
		} catch (Exception ex) {
			// ex.printStackTrace();
			Log.print("发送请求[" + postURL + "]失败," + ex.getMessage());
			return null;
		} finally {
			if (httpConn != null) {
				httpConn.disconnect();
			}
		}
	}
}
</span>

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。