package org.yeshi.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.Iterator; import java.util.Map; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.StringPart; import org.apache.commons.io.FileUtils; import org.yeshi.utils.entity.ProxyIP; import net.sf.json.JSONArray; public class HttpUtil { public static String getHost(String host) { try { URL url = new URL(host); return url.getHost(); } catch (MalformedURLException e) { e.printStackTrace(); } return ""; } public static String getShortLink(String url) { String totalUrl = String.format("http://api.t.sina.com.cn/short_url/shorten.json?source=3271760578&url_long=%s", URLEncoder.encode(url)); String result = get(totalUrl, null); JSONArray rtesultArray = JSONArray.fromObject(result); if (rtesultArray.size() > 0) { return rtesultArray.optJSONObject(0).optString("url_short"); } return null; } public static String get(String url) { return get(url, null); } /** * get请求 * * @param url * @param timeoutMS-请求超时时间 * @return */ public static String get(String url, int timeoutMS) { HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(timeoutMS); try { GetMethod method = new GetMethod(url); client.executeMethod(method); return method.getResponseBodyAsString(); } catch (Exception e) { } return null; } public static String get(String url, Map headers) { HttpClient client = new HttpClient(); try { GetMethod method = new GetMethod(url); if (headers != null) { Iterator keys = headers.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); method.addRequestHeader(key, headers.get(key)); } } client.executeMethod(method); return method.getResponseBodyAsString(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } public static String get(String url, Map headers, ProxyIP ipInfo) { HttpClient client = new HttpClient(); if (ipInfo != null) client.getHostConfiguration().setProxy(ipInfo.getIp(), ipInfo.getPort()); try { GetMethod method = new GetMethod(url); if (headers != null) { Iterator keys = headers.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); method.addRequestHeader(key, headers.get(key)); } } client.executeMethod(method); return method.getResponseBodyAsString(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } public static String getAsString(String url, String fromCharset, String toCharset) { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); try { client.executeMethod(method); String response = method.getResponseBodyAsString(); String s1 = new String(response.getBytes(fromCharset), toCharset); return s1; } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } public static String get(String url, Map params, Map headers) { HttpClient client = new HttpClient(); try { Iterator keys = params.keySet().iterator(); url += "?"; while (keys.hasNext()) { String key = keys.next(); url += String.format("%s=%s&", key, URLEncoder.encode(params.get(key), "UTF-8")); } GetMethod method = new GetMethod(url); if (headers != null) { keys = headers.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); headers.get(key); method.setRequestHeader(key, headers.get(key)); } } client.executeMethod(method); System.out.println(method.getResponseHeader("cookies")); String result = method.getResponseBodyAsString(); return result; } catch (Exception e) { e.printStackTrace(); } return ""; } public static InputStream getAsInputStream(String url) { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); try { client.executeMethod(method); return method.getResponseBodyAsStream(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 下载图片文件 * * @param url * @return */ public static InputStream downLoadImg(String url) throws org.yeshi.utils.exception.HttpException { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); try { client.executeMethod(method); Header contentTypeHeader = method.getResponseHeader("Content-Type"); if (contentTypeHeader == null || contentTypeHeader.getValue().contains("text")) throw new org.yeshi.utils.exception.HttpException(2, "图片下载出错"); return method.getResponseBodyAsStream(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static InputStream getAsInputStream(String url, Map headers) { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); Iterator keys = headers.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); method.setRequestHeader(key, headers.get(key)); } try { client.executeMethod(method); return method.getResponseBodyAsStream(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static InputStream getImage(String url) { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); try { method.setRequestHeader("Content-Type", "image/jpeg"); client.executeMethod(method); return method.getResponseBodyAsStream(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static String post(String url) { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); method.addRequestHeader("Content-Type", "text/html;charset=UTF-8"); method.setRequestHeader("Content-Type", "text/html;charset=UTF-8"); try { client.executeMethod(method); return convertInputStreamToString(method.getResponseBodyAsStream()); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } public static String post(String url, Map map) { Iterator its = map.keySet().iterator(); NameValuePair[] params = new NameValuePair[map.keySet().size()]; int p = 0; while (its.hasNext()) { String key = its.next(); NameValuePair np = new NameValuePair(key, map.get(key)); params[p] = np; p++; } HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); method.addRequestHeader("Content-Type", "text/html;charset=UTF-8"); method.setRequestHeader("Content-Type", "text/html;charset=UTF-8"); method.setRequestBody(params); try { client.executeMethod(method); return convertInputStreamToString(method.getResponseBodyAsStream()); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } public static String post(String url, Map map, Map headers, ProxyIP ipInfo) { HttpClient client = new HttpClient(); if (ipInfo != null) client.getHostConfiguration().setProxy(ipInfo.getIp(), ipInfo.getPort()); PostMethod pm = new PostMethod(url);// 创建HttpPost对象 NameValuePair[] ns = new NameValuePair[map.keySet().size()]; Iterator its = map.keySet().iterator(); int index = 0; while (its.hasNext()) { String key = its.next(); ns[index++] = (new NameValuePair(key, map.get(key))); } if (headers != null) { its = headers.keySet().iterator(); while (its.hasNext()) { String key = its.next(); pm.setRequestHeader(key, headers.get(key)); } } try { pm.setRequestBody(ns); client.executeMethod(pm); return pm.getResponseBodyAsString(); } catch (Exception e) { e.printStackTrace(); } return ""; } public static String post(String url, Map map, Map headers) { HttpClient client = new HttpClient(); PostMethod pm = new PostMethod(url);// 创建HttpPost对象 NameValuePair[] ns = new NameValuePair[map.keySet().size()]; Iterator its = map.keySet().iterator(); int index = 0; while (its.hasNext()) { String key = its.next(); ns[index++] = (new NameValuePair(key, map.get(key))); } if (headers != null) { its = headers.keySet().iterator(); while (its.hasNext()) { String key = its.next(); pm.setRequestHeader(key, headers.get(key)); } } try { pm.setRequestBody(ns); client.executeMethod(pm); return pm.getResponseBodyAsString(); } catch (Exception e) { e.printStackTrace(); } return ""; } private static String convertInputStreamToString(InputStream inputStream) { BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); StringBuffer stringBuffer = new StringBuffer(); String str = ""; try { while ((str = br.readLine()) != null) { stringBuffer.append(str); } } catch (IOException e) { e.printStackTrace(); } return stringBuffer.toString(); } @SuppressWarnings("deprecation") public static String post(String url, String entity) { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); method.addRequestHeader("Content-Type", "text/html;charset=UTF-8"); method.setRequestHeader("Content-Type", "text/html;charset=UTF-8"); method.setRequestBody(entity); try { client.executeMethod(method); return convertInputStreamToString(method.getResponseBodyAsStream()); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } public static String postInputStream(String url, File file) throws FileNotFoundException { HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(url); Part[] parts = { new StringPart("filename", file.getName()), new StringPart("filelength", file.length() + ""), new StringPart("content-type", "image/jpg"), new FilePart("file", file) }; postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); try { client.executeMethod(postMethod); return convertInputStreamToString(postMethod.getResponseBodyAsStream()); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } public static File downloadFile(String url, String targetPath) { try { URL httpurl = new URL(url); FileUtils.copyURLToFile(httpurl, new File(targetPath)); } catch (Exception e) { e.printStackTrace(); } File f = new File(targetPath); if (!f.exists() || f.length() <= 0) return null; return f; } @SuppressWarnings("deprecation") public static InputStream postForInputstream(String url, String entity) { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); method.addRequestHeader("Content-Type", "text/html;charset=UTF-8"); method.setRequestHeader("Content-Type", "text/html;charset=UTF-8"); method.setRequestBody(entity); try { client.executeMethod(method); return method.getResponseBodyAsStream(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static String post(String url, String fileKey, File f) { PostMethod filePost = new PostMethod(url); HttpClient client = new HttpClient(); try { Part[] parts = { new FilePart(fileKey, f) }; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { return filePost.getResponseBodyAsString(); } else { System.out.println("上传失败"); } } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } return null; } }