123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567 |
- package com.fourdage.base.common;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.io.UnsupportedEncodingException;
- import java.net.HttpURLConnection;
- import java.net.Socket;
- import java.net.URL;
- import java.net.URLConnection;
- import java.net.URLEncoder;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import java.util.Map.Entry;
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- 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.impl.client.DefaultHttpClient;
- import org.apache.http.message.BasicNameValuePair;
- public class HttpHelper {
-
- /**
- * POST请求
- *
- * @param urlStr 请求地址
- * @param params 参数字典
- * @param charset 编码,最好传“UTF-8”
- * @return
- * @exception RuntimeException
- */
- public static String sendPostByHttpUrlConnection(String urlStr, Map<String, Object> params, String charset) {
- StringBuffer resultBuffer = null;
- // 构建请求参数
- String sbParams= JoiningTogetherParams(params);
- HttpURLConnection con = null;
- OutputStreamWriter osw = null;
- BufferedReader br = null;
- // 发送请求
- try {
- URL url = new URL(urlStr);
- con = (HttpURLConnection) url.openConnection();
- con.setRequestMethod("POST");
- con.setDoOutput(true);
- con.setDoInput(true);
- con.setUseCaches(false);
- con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- if (sbParams != null && sbParams.length() > 0) {
- osw = new OutputStreamWriter(con.getOutputStream(), charset);
- osw.write(sbParams);
- osw.flush();
- }
- // 读取返回内容
- resultBuffer = new StringBuffer();
- int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
- if (contentLength > 0) {
- br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
- String temp;
- while ((temp = br.readLine()) != null) {
- resultBuffer.append(temp);
- }
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (osw != null) {
- try {
- osw.close();
- } catch (IOException e) {
- osw = null;
- throw new RuntimeException(e);
- } finally {
- if (con != null) {
- con.disconnect();
- con = null;
- }
- }
- }
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- br = null;
- throw new RuntimeException(e);
- } finally {
- if (con != null) {
- con.disconnect();
- con = null;
- }
- }
- }
- }
- return resultBuffer.toString();
- }
- public static String sendPostByUrlConnection(String urlStr, Map<String, Object> params, String charset) {
- StringBuffer resultBuffer = null;
- // 构建请求参数
- String sbParams= JoiningTogetherParams(params);
- URLConnection con = null;
- OutputStreamWriter osw = null;
- BufferedReader br = null;
- try {
- URL realUrl = new URL(urlStr);
- // 打开和URL之间的连接
- con = realUrl.openConnection();
- // 设置通用的请求属性
- con.setRequestProperty("accept", "*/*");
- con.setRequestProperty("connection", "Keep-Alive");
- con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
- // 发送POST请求必须设置如下两行
- con.setDoOutput(true);
- con.setDoInput(true);
- // 获取URLConnection对象对应的输出流
- osw = new OutputStreamWriter(con.getOutputStream(), charset);
- if (sbParams != null && sbParams.length() > 0) {
- // 发送请求参数
- osw.write(sbParams);
- // flush输出流的缓冲
- osw.flush();
- }
- // 定义BufferedReader输入流来读取URL的响应
- resultBuffer = new StringBuffer();
- int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
- if (contentLength > 0) {
- br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
- String temp;
- while ((temp = br.readLine()) != null) {
- resultBuffer.append(temp);
- }
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (osw != null) {
- try {
- osw.close();
- } catch (IOException e) {
- osw = null;
- throw new RuntimeException(e);
- }
- }
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- br = null;
- throw new RuntimeException(e);
- }
- }
- }
- return resultBuffer.toString();
- }
- public static String sendGetByHttpUrlConnection(String urlStr, Map<String, Object> params, String charset) {
- StringBuffer resultBuffer = null;
- // 构建请求参数
- String sbParams= JoiningTogetherParams(params);
- HttpURLConnection con = null;
- BufferedReader br = null;
- try {
- URL url = null;
- if (sbParams != null && sbParams.length() > 0) {
- url = new URL(urlStr + "?" + sbParams);
- } else {
- url = new URL(urlStr);
- }
- con = (HttpURLConnection) url.openConnection();
- con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- con.connect();
- resultBuffer = new StringBuffer();
- br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
- String temp;
- while ((temp = br.readLine()) != null) {
- resultBuffer.append(temp);
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- br = null;
- throw new RuntimeException(e);
- } finally {
- if (con != null) {
- con.disconnect();
- con = null;
- }
- }
- }
- }
- return resultBuffer.toString();
- }
- public static String sendGetByUrlConnection(String urlStr, Map<String, Object> params, String charset) {
- StringBuffer resultBuffer = null;
- // 构建请求参数
- String sbParams= JoiningTogetherParams(params);
- BufferedReader br = null;
- try {
- URL url = null;
- if (sbParams != null && sbParams.length() > 0) {
- url = new URL(urlStr + "?" + sbParams);
- } else {
- url = new URL(urlStr);
- }
- URLConnection con = url.openConnection();
- // 设置请求属性
- con.setRequestProperty("accept", "*/*");
- con.setRequestProperty("connection", "Keep-Alive");
- con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
- // 建立连接
- con.connect();
- resultBuffer = new StringBuffer();
- br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
- String temp;
- while ((temp = br.readLine()) != null) {
- resultBuffer.append(temp);
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- br = null;
- throw new RuntimeException(e);
- }
- }
- }
- return resultBuffer.toString();
- }
- public static String httpClientPost(String urlStr, Map<String, Object> params, String charset) {
- StringBuffer resultBuffer = null;
- HttpClient client = new DefaultHttpClient();
- HttpPost httpPost = new HttpPost(urlStr);
- // 构建请求参数
- List<NameValuePair> list = new ArrayList<NameValuePair>();
- Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
- while (iterator.hasNext()) {
- Entry<String, Object> elem = iterator.next();
- list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
- }
- BufferedReader br = null;
- try {
- if (list.size() > 0) {
- UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
- httpPost.setEntity(entity);
- }
- HttpResponse response = client.execute(httpPost);
- // 读取服务器响应数据
- resultBuffer = new StringBuffer();
- br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
- String temp;
- while ((temp = br.readLine()) != null) {
- resultBuffer.append(temp);
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- br = null;
- throw new RuntimeException(e);
- }
- }
- }
- return resultBuffer.toString();
- }
- public static String httpClientGet(String urlStr, Map<String, Object> params, String charset) {
- StringBuffer resultBuffer = null;
- HttpClient client = new DefaultHttpClient();
- BufferedReader br = null;
- // 构建请求参数
- StringBuffer sbParams = new StringBuffer();
- if (params != null && params.size() > 0) {
- for (Entry<String, Object> entry : params.entrySet()) {
- sbParams.append(entry.getKey());
- sbParams.append("=");
- try {
- sbParams.append(URLEncoder.encode(String.valueOf(entry.getValue()), charset));
- } catch (UnsupportedEncodingException e) {
- throw new RuntimeException(e);
- }
- sbParams.append("&");
- }
- }
- if (sbParams != null && sbParams.length() > 0) {
- urlStr = urlStr + "?" + sbParams.substring(0, sbParams.length() - 1);
- }
- HttpGet httpGet = new HttpGet(urlStr);
- try {
- HttpResponse response = client.execute(httpGet);
- // 读取服务器响应数据
- br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
- String temp;
- resultBuffer = new StringBuffer();
- while ((temp = br.readLine()) != null) {
- resultBuffer.append(temp);
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- br = null;
- throw new RuntimeException(e);
- }
- }
- }
- return resultBuffer.toString();
- }
- public static String sendSocketPost(String urlStr, Map<String, Object> params, String charset) {
- String result = "";
- // 构建请求参数
- StringBuffer sbParams = new StringBuffer();
- if (params != null && params.size() > 0) {
- for (Entry<String, Object> entry : params.entrySet()) {
- sbParams.append(entry.getKey());
- sbParams.append("=");
- sbParams.append(entry.getValue());
- sbParams.append("&");
- }
- }
- Socket socket = null;
- OutputStreamWriter osw = null;
- InputStream is = null;
- try {
- URL url = new URL(urlStr);
- String host = url.getHost();
- int port = url.getPort();
- if (-1 == port) {
- port = 80;
- }
- String path = url.getPath();
- socket = new Socket(host, port);
- StringBuffer sb = new StringBuffer();
- sb.append("POST " + path + " HTTP/1.1\r\n");
- sb.append("Host: " + host + "\r\n");
- sb.append("Connection: Keep-Alive\r\n");
- sb.append("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r\n");
- sb.append("Content-Length: ").append(sb.toString().getBytes().length).append("\r\n");
- // 这里一个回车换行,表示消息头写完,不然服务器会继续等待
- sb.append("\r\n");
- if (sbParams != null && sbParams.length() > 0) {
- sb.append(sbParams.substring(0, sbParams.length() - 1));
- }
- osw = new OutputStreamWriter(socket.getOutputStream());
- osw.write(sb.toString());
- osw.flush();
- is = socket.getInputStream();
- String line = null;
- // 服务器响应体数据长度
- int contentLength = 0;
- // 读取http响应头部信息
- do {
- line = readLine(is, 0, charset);
- if (line.startsWith("Content-Length")) {
- // 拿到响应体内容长度
- contentLength = Integer.parseInt(line.split(":")[1].trim());
- }
- // 如果遇到了一个单独的回车换行,则表示请求头结束
- } while (!line.equals("\r\n"));
- // 读取出响应体数据(就是你要的数据)
- result = readLine(is, contentLength, charset);
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (osw != null) {
- try {
- osw.close();
- } catch (IOException e) {
- osw = null;
- throw new RuntimeException(e);
- } finally {
- if (socket != null) {
- try {
- socket.close();
- } catch (IOException e) {
- socket = null;
- throw new RuntimeException(e);
- }
- }
- }
- }
- if (is != null) {
- try {
- is.close();
- } catch (IOException e) {
- is = null;
- throw new RuntimeException(e);
- } finally {
- if (socket != null) {
- try {
- socket.close();
- } catch (IOException e) {
- socket = null;
- throw new RuntimeException(e);
- }
- }
- }
- }
- }
- return result;
- }
- public static String sendSocketGet(String urlStr, Map<String, Object> params, String charset) {
- String result = "";
- // 构建请求参数
- StringBuffer sbParams = new StringBuffer();
- if (params != null && params.size() > 0) {
- for (Entry<String, Object> entry : params.entrySet()) {
- sbParams.append(entry.getKey());
- sbParams.append("=");
- sbParams.append(entry.getValue());
- sbParams.append("&");
- }
- }
- Socket socket = null;
- OutputStreamWriter osw = null;
- InputStream is = null;
- try {
- URL url = new URL(urlStr);
- String host = url.getHost();
- int port = url.getPort();
- if (-1 == port) {
- port = 80;
- }
- String path = url.getPath();
- socket = new Socket(host, port);
- StringBuffer sb = new StringBuffer();
- sb.append("GET " + path + " HTTP/1.1\r\n");
- sb.append("Host: " + host + "\r\n");
- sb.append("Connection: Keep-Alive\r\n");
- sb.append("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r\n");
- sb.append("Content-Length: ").append(sb.toString().getBytes().length).append("\r\n");
- // 这里一个回车换行,表示消息头写完,不然服务器会继续等待
- sb.append("\r\n");
- if (sbParams != null && sbParams.length() > 0) {
- sb.append(sbParams.substring(0, sbParams.length() - 1));
- }
- osw = new OutputStreamWriter(socket.getOutputStream());
- osw.write(sb.toString());
- osw.flush();
- is = socket.getInputStream();
- String line = null;
- // 服务器响应体数据长度
- int contentLength = 0;
- // 读取http响应头部信息
- do {
- line = readLine(is, 0, charset);
- if (line.startsWith("Content-Length")) {
- // 拿到响应体内容长度
- contentLength = Integer.parseInt(line.split(":")[1].trim());
- }
- // 如果遇到了一个单独的回车换行,则表示请求头结束
- } while (!line.equals("\r\n"));
- // 读取出响应体数据(就是你要的数据)
- result = readLine(is, contentLength, charset);
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (osw != null) {
- try {
- osw.close();
- } catch (IOException e) {
- osw = null;
- throw new RuntimeException(e);
- } finally {
- if (socket != null) {
- try {
- socket.close();
- } catch (IOException e) {
- socket = null;
- throw new RuntimeException(e);
- }
- }
- }
- }
- if (is != null) {
- try {
- is.close();
- } catch (IOException e) {
- is = null;
- throw new RuntimeException(e);
- } finally {
- if (socket != null) {
- try {
- socket.close();
- } catch (IOException e) {
- socket = null;
- throw new RuntimeException(e);
- }
- }
- }
- }
- }
- return result;
- }
- private static String readLine(InputStream is, int contentLength, String charset) throws IOException {
- List<Byte> lineByte = new ArrayList<Byte>();
- byte tempByte;
- int cumsum = 0;
- if (contentLength != 0) {
- do {
- tempByte = (byte) is.read();
- lineByte.add(Byte.valueOf(tempByte));
- cumsum++;
- } while (cumsum < contentLength);// cumsum等于contentLength表示已读完
- } else {
- do {
- tempByte = (byte) is.read();
- lineByte.add(Byte.valueOf(tempByte));
- } while (tempByte != 10);// 换行符的ascii码值为10
- }
- byte[] resutlBytes = new byte[lineByte.size()];
- for (int i = 0; i < lineByte.size(); i++) {
- resutlBytes[i] = (lineByte.get(i)).byteValue();
- }
- return new String(resutlBytes, charset);
- }
-
- private static String JoiningTogetherParams(Map<String, Object> params){
- StringBuffer sbParams = new StringBuffer();
- if (params != null && params.size() > 0) {
- for (Entry<String, Object> e : params.entrySet()) {
- sbParams.append(e.getKey());
- sbParams.append("=");
- sbParams.append(e.getValue());
- sbParams.append("&");
- }
- return sbParams.substring(0, sbParams.length() - 1);
- }
- return "";
- }
- }
|