url 解析工具
package org.iam.commpoment.timertask.demo;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpUtil {
private static Log log=LogFactory.getLog(HttpUtil.class);
/**
* 采用POST方式进行
* @param paramStr
* @return
*/
public static String POST_API(String urlStr,String paramStr,Map<String,String> headers) {
log.debug(urlStr+","+paramStr+","+headers);
BufferedReader br=null;
OutputStream os=null;
StringBuffer strBuf=new StringBuffer();
try {
URL url=new URL(urlStr);
HttpURLConnection con=(HttpURLConnection) url.openConnection();
con.setReadTimeout(5000);//5秒过期
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
for (Map.Entry<String,String> entry : headers.entrySet()) {
con.setRequestProperty(entry.getKey(), entry.getValue());
}
os=con.getOutputStream();
os.write(paramStr.getBytes("UTF-8"));
if(con.getResponseCode()==200){
br=new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
String line;
while((line=br.readLine())!=null){
strBuf.append(line);
}
}
} catch (Exception e) {
log.error("post_api error",e);
} finally{
if(os!=null){
try{os.close();}catch(Exception e){}
}
if(br!=null){
try{br.close();}catch(Exception e){}
}
}
return strBuf.toString();
}
public static String GET_API(String urlStr,Map<String,String> headers) {
log.debug(urlStr+","+headers);
BufferedReader br=null;
OutputStream os=null;
StringBuffer strBuf=new StringBuffer();
try {
URL url=new URL(urlStr);
HttpURLConnection con=(HttpURLConnection) url.openConnection();
con.setReadTimeout(5000);//5秒过期
for (Map.Entry<String,String> entry : headers.entrySet()) {
con.setRequestProperty(entry.getKey(), entry.getValue());
}
br=new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
String line;
while((line=br.readLine())!=null){
strBuf.append(line);
}
} catch (Exception e) {
log.error("get_api error",e);
} finally{
if(os!=null){
try{os.close();}catch(Exception e){}
}
if(br!=null){
try{br.close();}catch(Exception e){}
}
}
return strBuf.toString();
}
public static String post(String requestUrl, String accessToken, String params)
throws Exception {
String contentType = "application/x-www-form-urlencoded";
return HttpUtil.post(requestUrl, accessToken, contentType, params);
}
public static String post(String requestUrl, String accessToken, String contentType, String params)
throws Exception {
String encoding = "UTF-8";
if (requestUrl.contains("nlp")) {
encoding = "GBK";
}
return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
}
public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
throws Exception {
String url = requestUrl + "?access_token=" + accessToken;
return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
}
public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
throws Exception {
URL url = new URL(generalUrl);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// 设置通用的请求属性
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
// 得到请求的输出流对象
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(params.getBytes(encoding));
out.flush();
out.close();
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> headers = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : headers.keySet()) {
//System.err.println(key + "--->" + headers.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = null;
in = new BufferedReader(
new InputStreamReader(connection.getInputStream(), encoding));
String result = "";
String getLine;
while ((getLine = in.readLine()) != null) {
result += getLine;
}
in.close();
// System.err.println("result:" + result);
return result;
}
public static String postGeneralUrl(String generalUrl, String contentType,
Map<String, Object> params, String encoding) {
String content = null;
try {
HttpPost post = new HttpPost(generalUrl);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(5000).setConnectTimeout(5000).build();
post.setConfig(requestConfig);
CloseableHttpClient httpClient = HttpClients.createDefault();
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
for (Map.Entry<String, Object> val : params.entrySet())
list.add(new BasicNameValuePair(val.getKey(), String
.valueOf(val.getValue())));
post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
HttpResponse response = httpClient.execute(post);
content = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
return "";
}
return content;
}
public static JSONObject doPost(String path) throws Exception {
Thread.sleep(1000 * 1);
String content;
JSONObject json = new JSONObject();
HttpClient http = null;
CookieStore httpCookieStore = new BasicCookieStore();
http = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore).build();
// DefaultHttpClient client = new DefaultHttpClient();
//准备post请求 定义 一个httpget实现
HttpPost post = new HttpPost(path);
//执行一个Post请求
HttpResponse response = http.execute(post);
//获取服务器返回的状态码
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
//获取服务器返回的数据 以流的形式返回
InputStream inputStream = response.getEntity().getContent();
//把流转换成字符串
List<Cookie> cookies = httpCookieStore.getCookies();
json.put("cookie", cookies.get(0).getValue());
} else {
json.put("msg", "false");
}
return json;
}
}