码迷,mamicode.com
首页 > Web开发 > 详细

Httpclient

时间:2015-01-22 15:27:48      阅读:125      评论:0      收藏:0      [点我收藏+]

标签: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>

Httpclient

标签:httpclient

原文地址:http://blog.csdn.net/xuke6677/article/details/43019609

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!