1. 程式人生 > >HTTP請求

HTTP請求

throws log int utf-8 trac ges aps coder 內容

一:工具類HttpUtil

技術分享
package com.bw30.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; public class HttpUtil {
private static final int CONNECT_OUTTIME = 10000; private static final int READ_OUTTIME = 10000; private static final Logger logger = Logger.getLogger(HttpUtil.class); private static final String SERVLET_POST = "POST"; private static final String SERVLET_GET = "GET"; private static final
String SERVLET_DELETE = "DELETE"; private static final String SERVLET_PUT = "PUT"; public static String getRequetString(HttpServletRequest req) throws IOException { String returnStr = ""; BufferedInputStream bis = null; ByteArrayOutputStream bos = null; try { bis = new BufferedInputStream(req.getInputStream()); bos = new ByteArrayOutputStream(); int b = bis.read(); while (b >= 0) { bos.write(b); b = bis.read(); } returnStr = new String(bos.toByteArray(), "UTF-8"); bos.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (bis != null) { bis.close(); } if (bos != null) { bos.close(); } } catch (Exception e) { e.printStackTrace(); } } return returnStr.trim(); } /*** * 發送get請求 * @param url * @param enc * @return */ public static String getUrl(String serverUrl, String enc) { HttpURLConnection conn = null; BufferedReader br = null; StringBuffer response = new StringBuffer(); logger.info("Get請求:" + serverUrl); if (CommonTool.isStrEmpty(enc)) { enc = "UTF-8"; } try { URL url = new URL(serverUrl); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(CONNECT_OUTTIME); conn.setReadTimeout(READ_OUTTIME); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod(SERVLET_GET); conn.setRequestProperty("Content-Type", "text/html; charset=" + enc); conn.connect(); logger.info("響應代碼:" + conn.getResponseCode()); br = new BufferedReader(new InputStreamReader(conn.getInputStream(), enc)); String line; while ((line = br.readLine()) != null) { response.append(line + "\r\n"); } if (response.length() > 1) { response.delete(response.length() - 2, response.length()); } } catch (MalformedURLException e1) { logger.error("執行HTTP Get請求" + serverUrl + "時,發生MalformedURLException異常!", e1); } catch (ProtocolException e1) { logger.error("執行HTTP Get請求" + serverUrl + "時,發生ProtocolException異常!", e1); } catch (IOException e1) { logger.error("執行HTTP Get請求" + serverUrl + "時,發生IOException異常!", e1); } finally { try { if (br != null) { br.close(); br = null; } if (conn != null) { conn.disconnect(); conn = null; } } catch (IOException e) { } } logger.info("響應內容:" + response.toString()); return response.toString(); } public static String postUrl(String serverUrl, String content, String enc) { HttpURLConnection conn = null; BufferedOutputStream out = null; BufferedReader in = null; StringBuffer response = new StringBuffer(); if (content == null) { content = ""; } logger.info("Post請求:" + serverUrl); if (!content.isEmpty()) { logger.info("請求參數: " + content); } if (CommonTool.isStrEmpty(enc)) { enc = "UTF-8"; } try { URL url = new URL(serverUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Content-Length", Integer .toString(content.getBytes(enc).length)); // conn.setRequestProperty("Content-type", // "application/x-java-serialized-object");// application/x-www-form-urlencoded conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); conn.setRequestMethod(SERVLET_POST); conn.setConnectTimeout(CONNECT_OUTTIME); conn.setReadTimeout(READ_OUTTIME); conn.setDoOutput(true); conn.setDoInput(true); // @post xml out = new BufferedOutputStream(conn.getOutputStream()); StringBuffer buffer = new StringBuffer(content.length()); buffer.append(content); out.write(buffer.toString().getBytes(enc)); out.flush(); // @make xml logger.info("響應代碼:" + conn.getResponseCode()); in = new BufferedReader(new InputStreamReader( conn.getInputStream(), enc)); String line; while ((line = in.readLine()) != null) { response.append(line + "\r\n"); } if (response.length() > 1) { response.delete(response.length() - 2, response.length()); } } catch (MalformedURLException e1) { logger.error("執行HTTP Post請求" + serverUrl + "時,發生MalformedURLException異常!", e1); } catch (UnsupportedEncodingException e1) { logger.error("執行HTTP Post請求" + serverUrl + "時,發生UnsupportedEncodingException異常!", e1); } catch (ProtocolException e1) { logger.error("執行HTTP Post請求" + serverUrl + "時,發生ProtocolException異常!", e1); } catch (IOException e1) { logger.error("執行HTTP Post請求" + serverUrl + "時,發生IOException異常!", e1); } catch (Exception e1) { logger.error("執行HTTP Post請求" + serverUrl + "時,發生Exception異常!", e1); } finally { try { if (out != null) { out.close(); out = null; } if (in != null) { in.close(); in = null; } if (conn != null) { conn.disconnect(); conn = null; } } catch (IOException e) { } } logger.info("響應內容:" + response.toString()); return response.toString(); } public static String postXml(String serverUrl, String content, String enc) { HttpURLConnection conn = null; BufferedOutputStream out = null; BufferedReader in = null; StringBuffer response = new StringBuffer(); if (content == null) { content = ""; } logger.info("Post請求:" + serverUrl); if (!content.isEmpty()) { logger.info("請求參數: " + content); } if (CommonTool.isStrEmpty(enc)) { enc = "UTF-8"; } try { URL url = new URL(serverUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Content-Length", Integer.toString(content.getBytes(enc).length)); conn.setRequestProperty("Content-type", "text/html; charset=" + enc); conn.setRequestMethod(SERVLET_POST); conn.setConnectTimeout(CONNECT_OUTTIME); conn.setReadTimeout(READ_OUTTIME); conn.setDoOutput(true); conn.setDoInput(true); // @post xml out = new BufferedOutputStream(conn.getOutputStream()); StringBuffer buffer = new StringBuffer(content.length()); buffer.append(content); out.write(buffer.toString().getBytes(enc)); out.flush(); // @make xml logger.info("響應代碼:" + conn.getResponseCode()); in = new BufferedReader(new InputStreamReader( conn.getInputStream(), enc)); String line; while ((line = in.readLine()) != null) { response.append(line + "\r\n"); } if (response.length() > 1) { response.delete(response.length() - 2, response.length()); } } catch (MalformedURLException e1) { logger.error("執行HTTP Post請求" + serverUrl + "時,發生MalformedURLException異常!", e1); } catch (UnsupportedEncodingException e1) { logger.error("執行HTTP Post請求" + serverUrl + "時,發生UnsupportedEncodingException異常!", e1); } catch (ProtocolException e1) { logger.error("執行HTTP Post請求" + serverUrl + "時,發生ProtocolException異常!", e1); } catch (IOException e1) { logger.error("執行HTTP Post請求" + serverUrl + "時,發生IOException異常!", e1); } finally { try { if (out != null) { out.close(); out = null; } if (in != null) { in.close(); in = null; } if (conn != null) { conn.disconnect(); conn = null; } } catch (IOException e) { } } logger.info("響應內容:" + response.toString()); return response.toString(); } /** * * 執行一個HTTP POST 請求,返回響應字符串 * * @param url * 請求的URL地址 * @param params * 請求參數 * @return 返回響應字符串 * @throws UnsupportedEncodingException */ // public static String doPost(String url, Map<String, String> params) // throws UnsupportedEncodingException { // StringBuffer response = new StringBuffer(); // HttpClient client = new HttpClient(); // PostMethod method = new PostMethod(url); // // // 設置Http Post數據 // if (params != null) { // NameValuePair[] nameValuePairs = new NameValuePair[params.size()]; // int i = 0; // for (Map.Entry<String, String> entry : params.entrySet()) { // logger.info("post 請求參數名:" + entry.getKey() + " | 參數值:" // + entry.getValue()); // // (java.net.URLEncoder.encode(entry.getValue(),"UTF-8")) // nameValuePairs[i] = new NameValuePair(entry.getKey(), // (java.net.URLEncoder.encode(entry.getValue(), "UTF-8"))); // i++; // } // method.setRequestBody(nameValuePairs); // } // // try { // client.executeMethod(method); // if (method.getStatusCode() == HttpStatus.SC_OK) { // BufferedReader reader = new BufferedReader( // new InputStreamReader(method.getResponseBodyAsStream(), // "UTF-8")); // String line; // while ((line = reader.readLine()) != null) { // response.append(line); // } // reader.close(); // } // } catch (IOException e) { // logger.error("執行HTTP Post請求" + url + "時,發生異常!", e); // } finally { // method.releaseConnection(); // } // return response.toString(); // } // // public static String doGet(String url) { // StringBuffer response = new StringBuffer(); // HttpClient client = new HttpClient(); // GetMethod method = new GetMethod(url); // // try { // client.executeMethod(method); // if (method.getStatusCode() == HttpStatus.SC_OK) { // BufferedReader reader = new BufferedReader( // new InputStreamReader(method.getResponseBodyAsStream(), // "UTF-8")); // String line; // while ((line = reader.readLine()) != null) { // response.append(line + "\r\n"); // } // reader.close(); // } // } catch (HttpException e) { // logger.error("執行HTTP Get請求" + url + "時,發生HttpException異常!", e); // } catch (UnsupportedEncodingException e) { // logger.error("執行HTTP Get請求" + url // + "時,發生UnsupportedEncodingException異常!", e); // } catch (IOException e) { // logger.error("執行HTTP Get請求" + url + "時,發生IOException異常!", e); // } finally { // method.releaseConnection(); // } // // return response.toString(); // } /** * 生成請求內容字符串 * * @param datamap * @param params * @return * @throws UnsupportedEncodingException */ public static String generteRequestContent(Map<String, String> datamap, String[] params) { StringBuffer stringBuffer = new StringBuffer(); if (params == null) { return ""; } for (int i = 0; i < params.length; i++) { String val = (datamap != null) ? datamap.get(params[i]) : ""; if (val != null) { stringBuffer.append(params[i]); stringBuffer.append("="); stringBuffer.append(val); if (i != params.length - 1) { stringBuffer.append("&"); } } } // logger.info("請求參數: " + stringBuffer.toString()); return stringBuffer.toString(); } /** * 生成請求內容字符串(對val進行url編碼) * * @param datamap * @param enc 默認utf-8 * @return * @throws UnsupportedEncodingException */ public static String generteRequestContent(Map<String, String> datamap, String enc) throws UnsupportedEncodingException { StringBuffer buffer = new StringBuffer(); if (enc == null || enc.isEmpty()) { enc = "UTF-8";// 默認編碼 } Set<Entry<String, String>> entrySet = datamap.entrySet(); for (Entry<String, String> entry : entrySet) { String key = entry.getKey(); String val = entry.getValue(); if (key != null && !key.isEmpty() && val != null) { buffer.append("&"); buffer.append(key); buffer.append("="); buffer.append(URLEncoder.encode(val, enc)); } } if (buffer.length() > 0) { return buffer.substring(1).toString(); } return ""; // for (int i = 0; i < params.length; i++) { // String val = (datamap != null) ? datamap.get(params[i]) : ""; // if (val != null) { // buffer.append(params[i]); // buffer.append("="); // buffer.append(val); // // if (i != params.length - 1) { // buffer.append("&"); // } // } // } //// logger.info("請求參數: " + stringBuffer.toString()); // return buffer.toString(); } /** * 將字符串編碼成 Unicode 。 * * @param theString * 待轉換成Unicode編碼的字符串。 * @param escapeSpace * 是否忽略空格。 * @return 返回轉換後Unicode編碼的字符串。 */ public static String toUnicode(String theString, boolean escapeSpace) { int len = theString.length(); int bufLen = len * 2; if (bufLen < 0) { bufLen = Integer.MAX_VALUE; } StringBuffer outBuffer = new StringBuffer(bufLen); for (int x = 0; x < len; x++) { char aChar = theString.charAt(x); // Handle common case first, selecting largest block that // avoids the specials below if ((aChar > 61) && (aChar < 127)) { if (aChar == ‘\\‘) { outBuffer.append(‘\\‘); outBuffer.append(‘\\‘); continue; } outBuffer.append(aChar); continue; } switch (aChar) { case ‘ ‘: if (x == 0 || escapeSpace) outBuffer.append(‘\\‘); outBuffer.append(‘ ‘); break; case ‘\t‘: outBuffer.append(‘\\‘); outBuffer.append(‘t‘); break; case ‘\n‘: outBuffer.append(‘\\‘); outBuffer.append(‘n‘); break; case ‘\r‘: outBuffer.append(‘\\‘); outBuffer.append(‘r‘); break; case ‘\f‘: outBuffer.append(‘\\‘); outBuffer.append(‘f‘); break; case ‘=‘: // Fall through case ‘:‘: // Fall through case ‘#‘: // Fall through break; case ‘!‘: outBuffer.append(‘\\‘); outBuffer.append(aChar); break; default: if ((aChar < 0x0020) || (aChar > 0x007e)) { outBuffer.append(‘\\‘); outBuffer.append(‘u‘); outBuffer.append(toHex((aChar >> 12) & 0xF)); outBuffer.append(toHex((aChar >> 8) & 0xF)); outBuffer.append(toHex((aChar >> 4) & 0xF)); outBuffer.append(toHex(aChar & 0xF)); } else { outBuffer.append(aChar); } } } return outBuffer.toString(); } private static final char[] hexDigit = { ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘, ‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘ }; private static char toHex(int nibble) { return hexDigit[(nibble & 0xF)]; } }
View Code

HTTP請求