package com.vsstoo.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
public class GetPostUtil {
private static final String CHARSET = HTTP.UTF_8;
private static HttpClient httpClient;
/**
* 向指定url发送get请求
*/
public static String sendGet(String url, String params) {
String result = "";
BufferedReader br = null;
try {
String urlName = url + "?" + params;
URL realUrl = new URL(urlName);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.1;SV1)");
// 建立实际的连接
conn.connect();
// 获取所有响应头字段
// Map<String, List<String>> map=conn.getHeaderFields();
// 遍历所有的响应头字段
// for(String keyString;map.keySet()){
//
// }
br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
result += "\n" + line;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
/**
* 向指定url发送post请求
*/
public static String sendPost(String url, String params) {
String result = "";
BufferedReader br = null;
PrintWriter out = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.1;SV1)");
// 发送post请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(params);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URl的响应
br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
result += "\n" + line;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (br != null) {
br.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
private static synchronized HttpClient getHttpClient() {
// if (null == httpClient) {
HttpParams params = new BasicHttpParams();
// 设置一些基本参数
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProtocolParams
.setUserAgent(
params,
"Mozilla/5.0"
+ "(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
// 超时设置
/* 从连接池中取连接的超时时间 */
ConnManagerParams.setTimeout(params, 3 * 1000);
/* 连接超时 */
HttpConnectionParams.setConnectionTimeout(params, 4 * 1000);
/* 请求超时 */
HttpConnectionParams.setSoTimeout(params, 10 * 1000);
// 设置我们的HttpClient支持HTTP和HTTPS两种模式
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schReg.register(new Scheme("https",
SSLSocketFactory.getSocketFactory(), 443));
// 使用线程安全的连接管理来创建HttpClient
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
params, schReg);
if (httpClient == null) {
httpClient = new DefaultHttpClient(conMgr, params);
}
// }
return httpClient;
}
public static String post(String url, NameValuePair... params) {
HttpResponse response = null;
try {
// 编码参数
List<NameValuePair> formparams = new ArrayList<NameValuePair>(); // 请求参数
if (params != null) {
for (NameValuePair p : params) {
formparams.add(p);
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,
CHARSET);
// 创建POST请求
HttpPost request = new HttpPost(url);
request.setEntity(entity);
// 发送请求
HttpClient client = getHttpClient();
// HttpResponse response = client.execute(request);
response = client.execute(request);
System.out.println("response code===="
+ response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
System.out.println("response code===="
+ response.getStatusLine().getStatusCode());
return null;
}
HttpEntity resEntity = response.getEntity();
return (resEntity == null) ? null : EntityUtils.toString(resEntity,
CHARSET);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static String get(String url) {
HttpResponse response = null;
HttpGet request = new HttpGet(url);
HttpClient client = getHttpClient();
try {
response = client.execute(request);
System.out.println("response code===="
+ response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
System.out.println("response code===="
+ response.getStatusLine().getStatusCode());
return null;
}
HttpEntity resEntity = response.getEntity();
return (resEntity == null) ? null : EntityUtils.toString(resEntity,
CHARSET);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
}