package com.ming; import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map; public class HttpBaseUtil { /**
* 向指定的url发送post方法,并获取放回值
* @param url 发送的url
* @param param 发送的参数 参数形式a=2&b=2
* @param head 请求头设定
*/
public static String sendPostUrl(String url,String param,Map<String, String> head) throws Exception{
StringBuffer result=new StringBuffer();
PrintWriter out =null;
BufferedReader in=null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
HttpURLConnection conn =(HttpURLConnection)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)");
if(head!=null && !head.isEmpty()){
for (String key:head.keySet()){
conn.setRequestProperty(key, head.get(key));
}
}
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
throw new Exception("发送post出现异常."+e.getMessage());
}
return result.toString();
} }
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpUriRequest; import java.io.IOException; public class LocalHttpClient { private static LocalHttpClient localHttpClient;
protected HttpClient httpClient; private static int maxTotal = ;
private static int maxPerRoute = ;
public static void init(int maxTotal,int maxPerRoute){
LocalHttpClient.maxTotal = maxTotal;
LocalHttpClient.maxPerRoute = maxPerRoute;
} public static LocalHttpClient getInstance(){
if(localHttpClient != null){
return localHttpClient;
}else{
localHttpClient = new LocalHttpClient();
if(maxTotal > ){
localHttpClient.httpClient = HttpClientFactory.createHttpClient(maxTotal,maxPerRoute);
}else{
localHttpClient.httpClient = HttpClientFactory.createHttpClient();
}
return localHttpClient;
}
} public HttpResponse execute(HttpUriRequest request){
try {
return httpClient.execute(request);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
} public <T> T execute(HttpUriRequest request,ResponseHandler<T> responseHandler){
try {
return httpClient.execute(request, responseHandler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}