1. 程式人生 > >http 請求類

http 請求類

con exce div urn open www main out ack

package com.wenwo.platform.utils;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HttpClient { private static final Logger log = LoggerFactory.getLogger(HttpClient.class); private static HttpURLConnection conn = null;
/** * 向指定URL發送GET方法的請求 * @param url 發送請求的URL * @param param 請求參數,請求參數應該是name1=value1&name2=value2的形式 * @return URL所代表遠程資源的響應 */ public static String sendGet(String url) { String result = ""; BufferedReader in = null; try { URL realUrl
= new URL(url); // 打開和URL之間的連接 URLConnection conn = 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)"); // 建立實際的連接 conn.connect(); // 獲取所有響應頭字段 Map<String, List<String>> map = conn.getHeaderFields(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += "\n" + line; } } catch (Exception e) { log.error("HttpClient snedGet url:"+url+" error ->", e); } // 使用finally塊來關閉輸入流 finally { try { if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } /** * 向指定URL發送GET方法的請求 * @param url 發送請求的URL * @param param 請求參數,請求參數應該是name1=value1&name2=value2的形式 * @return URL所代表遠程資源的響應 */ public static String sendGet(String url,Map<String, Object> headerMap) { String result = ""; BufferedReader in = null; try { URL realUrl = new URL(url); // 打開和URL之間的連接 URLConnection conn = 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(headerMap != null) { Iterator<Map.Entry<String, Object>> it = headerMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> element = (Map.Entry<String, Object>) it .next(); conn.setRequestProperty(element.getKey(), element.getValue().toString()); } } // 建立實際的連接 conn.connect(); // 獲取所有響應頭字段 Map<String, List<String>> map = conn.getHeaderFields(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8")); String line; while ((line = in.readLine()) != null) { result += "\n" + line; } } catch (Exception e) { log.error("HttpClient snedGet url:"+url+" error ->", e); } // 使用finally塊來關閉輸入流 finally { try { if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } public static String get(String urlAddr, Map<String, Object> paramMap) throws Exception { String content = ""; StringBuffer params = new StringBuffer(); if(paramMap != null) { Iterator<Map.Entry<String, Object>> it = paramMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> element = (Map.Entry<String, Object>) it .next(); params.append((String) element.getKey()); params.append("="); params.append(element.getValue()); params.append("&"); } } if (params.length() > 0) { params.deleteCharAt(params.length() - 1); } BufferedReader br = null; try { URL url = new URL(urlAddr); //new URL(urlAddr + "?" + params.toString()); if(params.length()>0){ url = new URL(urlAddr + "?" + params.toString()); } conn = ((HttpURLConnection) url.openConnection()); conn.setConnectTimeout(3000); conn.setReadTimeout(3000); conn.setDoOutput(false); conn.setRequestMethod("GET"); conn.setUseCaches(false); conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", "0"); conn.setDoInput(true); conn.connect(); int code = conn.getResponseCode(); if (code != 200) { log.info("ERROR===" + code); } else { InputStream in = conn.getInputStream(); System.out.println("in.available():"+in.available()); br = new BufferedReader(new InputStreamReader(in, "UTF-8")); String line = ""; while ((line = br.readLine()) != null){ content = content + line + "\r\n"; } } } catch (Exception e) { e.printStackTrace(); log.error("urlAddr:"+urlAddr+" get error.->" + params.toString(), e); } finally { if (br != null){ br.close(); } if (conn!= null)conn.disconnect(); } return content; } public static String post(String urlAddr, Map<String, Object> paramMap) throws Exception { String content = ""; StringBuffer params = new StringBuffer(); Iterator<Map.Entry<String, Object>> it = paramMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> element = (Map.Entry<String, Object>) it .next(); params.append((String) element.getKey()); params.append("="); params.append(element.getValue()); params.append("&"); } if (params.length() > 0) { params.deleteCharAt(params.length() - 1); } BufferedReader br = null; try { URL url = new URL(urlAddr); conn = ((HttpURLConnection) url.openConnection()); conn.setConnectTimeout(3000); conn.setReadTimeout(3000); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(params.length())); conn.setDoInput(true); conn.connect(); OutputStreamWriter out = new OutputStreamWriter( conn.getOutputStream(), "UTF-8"); out.write(params.toString()); out.flush(); out.close(); int code = conn.getResponseCode(); if (code != 200) { log.info("ERROR===" + code); InputStream in = conn.getInputStream(); br = new BufferedReader(new InputStreamReader( in, "UTF-8")); String line = ""; while ((line = br.readLine()) != null) content = content + line + "\r\n"; } else { InputStream in = conn.getInputStream(); br = new BufferedReader(new InputStreamReader( in, "UTF-8")); String line = ""; while ((line = br.readLine()) != null) content = content + line + "\r\n"; } } catch (Exception e) { e.printStackTrace(); log.error("urlAddr:"+urlAddr+" post error. ->" + params.toString(), e); } finally { if (conn!=null)conn.disconnect(); if (br != null){ br.close(); } } return content; } public static String sendPost(String urlAddr, Map<String, Object> paramMap, Map<String, Object> headerMap) throws Exception { String content = ""; HttpURLConnection conn = null; StringBuffer params = new StringBuffer(); Iterator<Map.Entry<String, Object>> it = paramMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> element = (Map.Entry<String, Object>) it .next(); params.append((String) element.getKey()); params.append("="); params.append(element.getValue()); params.append("&"); } if (params.length() > 0) { params.deleteCharAt(params.length() - 1); } BufferedReader br = null; try { URL url = new URL(urlAddr); conn = ((HttpURLConnection) url.openConnection()); conn.setConnectTimeout(3000); conn.setReadTimeout(3000); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setUseCaches(false); conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length",String.valueOf(params.length())); Iterator<Map.Entry<String, Object>> iter = headerMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, Object> element = (Map.Entry<String, Object>) iter .next(); conn.setRequestProperty(element.getKey(), (String)element.getValue()); } conn.setDoInput(true); conn.connect(); OutputStreamWriter out = new OutputStreamWriter( conn.getOutputStream(), "UTF-8"); out.write(params.toString()); out.flush(); out.close(); int code = conn.getResponseCode(); if (code != 200) { log.info("ERROR===" + code); InputStream in = conn.getInputStream(); br = new BufferedReader(new InputStreamReader( in, "UTF-8")); String line = ""; while ((line = br.readLine()) != null){ content = content + line + "\r\n"; } } else { InputStream in = conn.getInputStream(); br = new BufferedReader(new InputStreamReader(in, "UTF-8")); String line = ""; while ((line = br.readLine()) != null){ content = content + line + "\r\n"; } } log.info(urlAddr + "post info -->" + params.toString() + " result code: " + code + " , data : " + content); } catch (Exception e) { e.printStackTrace(); log.error("urlAddr:" + urlAddr+" post error.-> " + params.toString(), e); } finally { if (conn!=null) conn.disconnect(); if (br != null){ br.close(); } } return content; } public static String post(String urlAddr, Map<String, Object> paramMap, Map<String, Object> headerMap) throws Exception { String content = ""; HttpURLConnection conn = null; StringBuffer params = new StringBuffer(); Iterator<Map.Entry<String, Object>> it = paramMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> element = (Map.Entry<String, Object>) it .next(); params.append((String) element.getKey()); params.append("="); params.append(element.getValue()); params.append("&"); } if (params.length() > 0) { params.deleteCharAt(params.length() - 1); } BufferedReader br = null; try { URL url = new URL(urlAddr); conn = ((HttpURLConnection) url.openConnection()); conn.setConnectTimeout(3000); conn.setReadTimeout(3000); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setUseCaches(false); conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length",String.valueOf(params.length())); Iterator<Map.Entry<String, Object>> iter = headerMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, Object> element = (Map.Entry<String, Object>) iter .next(); conn.setRequestProperty(element.getKey(), (String)element.getValue()); } conn.setDoInput(true); conn.connect(); OutputStreamWriter out = new OutputStreamWriter( conn.getOutputStream(), "UTF-8"); out.write(params.toString()); out.flush(); out.close(); int code = conn.getResponseCode(); if (code != 200) { log.info("ERROR===" + code); InputStream in = conn.getInputStream(); br = new BufferedReader(new InputStreamReader( in, "UTF-8")); String line = ""; while ((line = br.readLine()) != null) content = content + line + "\r\n"; } else { InputStream in = conn.getInputStream(); br = new BufferedReader(new InputStreamReader( in, "UTF-8")); String line = ""; while ((line = br.readLine()) != null) content = content + line + "\r\n"; } } catch (Exception e) { e.printStackTrace(); log.error("urlAddr:"+urlAddr+" post error.-> " + params.toString(), e); } finally { if (conn!=null) conn.disconnect(); if (br != null){ br.close(); } } return content; } public static String post(String urlAddr, String json) throws Exception { String content = ""; HttpURLConnection urlConnection = null; BufferedReader br = null; try { URL url = new URL(urlAddr); urlConnection = (HttpURLConnection) url.openConnection(); // 設置doOutput屬性為true表示將使用此urlConnection寫入數據 urlConnection.setDoOutput(true); urlConnection.setConnectTimeout(3000); urlConnection.setReadTimeout(3000); // 定義待寫入數據的內容類型,我們設置為application/x-www-form-urlencoded類型 urlConnection.setRequestProperty("content-type", "text/plain"); urlConnection.setRequestProperty("user-agent", "curl/7.12.1"); urlConnection.setRequestProperty("host", "data.zz.baidu.com"); urlConnection.setRequestProperty("content-length", String.valueOf(json.length()) ); // 得到請求的輸出流對象 OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream()); // 把數據寫入請求的Body out.write(json); out.flush(); out.close(); int code = urlConnection.getResponseCode(); if (code != 200) { log.info("urlAddr:"+urlAddr+" code ERROR===" + code); } else { InputStream in = urlConnection.getInputStream(); br = new BufferedReader(new InputStreamReader( in, "UTF-8")); String line = ""; while ((line = br.readLine()) != null) content = content + line + "\r\n"; } } catch (Exception e) { e.printStackTrace(); log.error("urlAddr:"+urlAddr+" post error->" + json, e); } finally { if (urlConnection!=null) urlConnection.disconnect(); if (br != null){ br.close(); } } return content; } public static String postBuiness(String urlAddr, String json) { String content = ""; HttpURLConnection urlConnection = null; BufferedReader br = null; try { URL url = new URL(urlAddr); urlConnection = (HttpURLConnection) url.openConnection(); // 設置doOutput屬性為true表示將使用此urlConnection寫入數據 urlConnection.setDoOutput(true); // 定義待寫入數據的內容類型,我們設置為application/x-www-form-urlencoded類型 urlConnection.setRequestProperty("content-type", "text/plain"); urlConnection.setRequestProperty("user-agent", "curl/7.12.1"); urlConnection.setRequestProperty("host", "data.zz.baidu.com"); urlConnection.setRequestProperty("content-length", String.valueOf(json.length()) ); // 得到請求的輸出流對象 OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream()); // 把數據寫入請求的Body out.write(json); out.flush(); out.close(); int code = urlConnection.getResponseCode(); if (code != 200) { log.info("ERROR===" + code); } else { InputStream in = urlConnection.getInputStream(); br = new BufferedReader(new InputStreamReader( in, "UTF-8")); String line = ""; while ((line = br.readLine()) != null) content = content + line + "\r\n"; } } catch (Exception e) { e.printStackTrace(); log.error("urlAddr:"+urlAddr+" post error->" + json, e); } finally { if(urlConnection!=null)urlConnection.disconnect(); if (br != null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return content; } public static void main(String[] args) throws Exception { // String urlAddr = "http://api.weibo.com/2/proxy/badges/issue.json"; String ak = "4CZXhoWckYANMkvlCdZNy0kjtS4Aqjqk"; // params.put("source", "2067112424"); // params.put("uids", "2365944120"); // params.put("badge_id", "sAFStotI"); Map<String, Object> headers = new HashMap<String, Object>(); // HttpClient client = new HttpClient(); String urlAddr = "http://10.8.2.6:9200/_analyze?pretty&analyzer=ik_smart"; String result = client.post(urlAddr, "感冒的時候,最不易吃哪些東西???"); System.out.println(result); } }

package com.wenwo.platform.utils;

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLConnection;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
public class HttpClient {private static final Logger log = LoggerFactory.getLogger(HttpClient.class);
private static HttpURLConnection conn = null; /** * 向指定URL發送GET方法的請求 * @param url 發送請求的URL * @param param 請求參數,請求參數應該是name1=value1&name2=value2的形式 * @return URL所代表遠程資源的響應 */ public static String sendGet(String url) { String result = ""; BufferedReader in = null; try { URL realUrl = new URL(url); // 打開和URL之間的連接 URLConnection conn = 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)"); // 建立實際的連接 conn.connect(); // 獲取所有響應頭字段 Map<String, List<String>> map = conn.getHeaderFields(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += "\n" + line; } } catch (Exception e) { log.error("HttpClient snedGet url:"+url+" error ->", e); } // 使用finally塊來關閉輸入流 finally { try { if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } /** * 向指定URL發送GET方法的請求 * @param url 發送請求的URL * @param param 請求參數,請求參數應該是name1=value1&name2=value2的形式 * @return URL所代表遠程資源的響應 */ public static String sendGet(String url,Map<String, Object> headerMap) { String result = ""; BufferedReader in = null; try { URL realUrl = new URL(url); // 打開和URL之間的連接 URLConnection conn = 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(headerMap != null) { Iterator<Map.Entry<String, Object>> it = headerMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> element = (Map.Entry<String, Object>) it .next(); conn.setRequestProperty(element.getKey(), element.getValue().toString()); } } // 建立實際的連接 conn.connect(); // 獲取所有響應頭字段 Map<String, List<String>> map = conn.getHeaderFields(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8")); String line; while ((line = in.readLine()) != null) { result += "\n" + line; } } catch (Exception e) { log.error("HttpClient snedGet url:"+url+" error ->", e); } // 使用finally塊來關閉輸入流 finally { try { if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } public static String get(String urlAddr, Map<String, Object> paramMap) throws Exception {String content = "";StringBuffer params = new StringBuffer();if(paramMap != null) {Iterator<Map.Entry<String, Object>> it = paramMap.entrySet().iterator();while (it.hasNext()) {Map.Entry<String, Object> element = (Map.Entry<String, Object>) it.next();params.append((String) element.getKey());params.append("=");params.append(element.getValue());params.append("&");}}
if (params.length() > 0) {params.deleteCharAt(params.length() - 1);}BufferedReader br = null;try {URL url = new URL(urlAddr); //new URL(urlAddr + "?" + params.toString());if(params.length()>0){url = new URL(urlAddr + "?" + params.toString());}conn = ((HttpURLConnection) url.openConnection());conn.setConnectTimeout(3000); conn.setReadTimeout(3000); conn.setDoOutput(false);conn.setRequestMethod("GET");conn.setUseCaches(false);conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");conn.setRequestProperty("Content-Length", "0");conn.setDoInput(true);conn.connect();
int code = conn.getResponseCode();if (code != 200) {log.info("ERROR===" + code);} else {InputStream in = conn.getInputStream();System.out.println("in.available():"+in.available());br = new BufferedReader(new InputStreamReader(in, "UTF-8"));String line = "";while ((line = br.readLine()) != null){content = content + line + "\r\n";}}} catch (Exception e) { e.printStackTrace();log.error("urlAddr:"+urlAddr+" get error.->" + params.toString(), e);} finally { if (br != null){ br.close(); }if (conn!= null)conn.disconnect();}return content;}public static String post(String urlAddr, Map<String, Object> paramMap)throws Exception {String content = "";StringBuffer params = new StringBuffer();Iterator<Map.Entry<String, Object>> it = paramMap.entrySet().iterator();while (it.hasNext()) {Map.Entry<String, Object> element = (Map.Entry<String, Object>) it.next();params.append((String) element.getKey());params.append("=");params.append(element.getValue());params.append("&");}
if (params.length() > 0) {params.deleteCharAt(params.length() - 1);}BufferedReader br = null;try {URL url = new URL(urlAddr);conn = ((HttpURLConnection) url.openConnection());conn.setConnectTimeout(3000); conn.setReadTimeout(3000); conn.setDoOutput(true);conn.setRequestMethod("POST");conn.setUseCaches(false);conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");conn.setRequestProperty("Content-Length",String.valueOf(params.length()));conn.setDoInput(true);conn.connect();
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");out.write(params.toString());out.flush();out.close();
int code = conn.getResponseCode();if (code != 200) {log.info("ERROR===" + code);InputStream in = conn.getInputStream();br = new BufferedReader(new InputStreamReader(in, "UTF-8"));String line = "";while ((line = br.readLine()) != null)content = content + line + "\r\n";} else {InputStream in = conn.getInputStream();br = new BufferedReader(new InputStreamReader(in, "UTF-8"));String line = "";while ((line = br.readLine()) != null)content = content + line + "\r\n";}} catch (Exception e) { e.printStackTrace();log.error("urlAddr:"+urlAddr+" post error. ->" + params.toString(), e);} finally {if (conn!=null)conn.disconnect();if (br != null){ br.close();}}return content;}public static String sendPost(String urlAddr, Map<String, Object> paramMap, Map<String, Object> headerMap) throws Exception { String content = ""; HttpURLConnection conn = null; StringBuffer params = new StringBuffer(); Iterator<Map.Entry<String, Object>> it = paramMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> element = (Map.Entry<String, Object>) it .next(); params.append((String) element.getKey()); params.append("="); params.append(element.getValue()); params.append("&"); }
if (params.length() > 0) { params.deleteCharAt(params.length() - 1); } BufferedReader br = null; try { URL url = new URL(urlAddr); conn = ((HttpURLConnection) url.openConnection()); conn.setConnectTimeout(3000); conn.setReadTimeout(3000); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setUseCaches(false); conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length",String.valueOf(params.length())); Iterator<Map.Entry<String, Object>> iter = headerMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, Object> element = (Map.Entry<String, Object>) iter .next(); conn.setRequestProperty(element.getKey(), (String)element.getValue()); } conn.setDoInput(true); conn.connect();
OutputStreamWriter out = new OutputStreamWriter( conn.getOutputStream(), "UTF-8"); out.write(params.toString()); out.flush(); out.close(); int code = conn.getResponseCode(); if (code != 200) { log.info("ERROR===" + code); InputStream in = conn.getInputStream();
br = new BufferedReader(new InputStreamReader( in, "UTF-8")); String line = ""; while ((line = br.readLine()) != null){ content = content + line + "\r\n"; } } else { InputStream in = conn.getInputStream(); br = new BufferedReader(new InputStreamReader(in, "UTF-8")); String line = ""; while ((line = br.readLine()) != null){ content = content + line + "\r\n"; } } log.info(urlAddr + "post info -->" + params.toString() + " result code: " + code + " , data : " + content); } catch (Exception e) { e.printStackTrace(); log.error("urlAddr:" + urlAddr+" post error.-> " + params.toString(), e); } finally { if (conn!=null) conn.disconnect(); if (br != null){ br.close(); } } return content; }public static String post(String urlAddr, Map<String, Object> paramMap, Map<String, Object> headerMap)throws Exception { String content = "";HttpURLConnection conn = null;StringBuffer params = new StringBuffer();Iterator<Map.Entry<String, Object>> it = paramMap.entrySet().iterator();while (it.hasNext()) {Map.Entry<String, Object> element = (Map.Entry<String, Object>) it.next();params.append((String) element.getKey());params.append("=");params.append(element.getValue());params.append("&");}
if (params.length() > 0) {params.deleteCharAt(params.length() - 1);}BufferedReader br = null;try {URL url = new URL(urlAddr);conn = ((HttpURLConnection) url.openConnection());conn.setConnectTimeout(3000);conn.setReadTimeout(3000); conn.setDoOutput(true);conn.setRequestMethod("POST");conn.setUseCaches(false);conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");conn.setRequestProperty("Content-Length",String.valueOf(params.length()));Iterator<Map.Entry<String, Object>> iter = headerMap.entrySet().iterator();while (iter.hasNext()) {Map.Entry<String, Object> element = (Map.Entry<String, Object>) iter.next();conn.setRequestProperty(element.getKey(),(String)element.getValue());}conn.setDoInput(true);conn.connect();
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");out.write(params.toString());out.flush();out.close();
int code = conn.getResponseCode();if (code != 200) {log.info("ERROR===" + code);InputStream in = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(in, "UTF-8"));String line = "";while ((line = br.readLine()) != null)content = content + line + "\r\n";} else {InputStream in = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(in, "UTF-8"));String line = "";while ((line = br.readLine()) != null)content = content + line + "\r\n";}} catch (Exception e) { e.printStackTrace();log.error("urlAddr:"+urlAddr+" post error.-> " + params.toString(), e);} finally {if (conn!=null) conn.disconnect();if (br != null){ br.close();}}return content;}
public static String post(String urlAddr, String json) throws Exception {String content = "";HttpURLConnection urlConnection = null;BufferedReader br = null;try { URL url = new URL(urlAddr); urlConnection = (HttpURLConnection) url.openConnection(); // 設置doOutput屬性為true表示將使用此urlConnection寫入數據 urlConnection.setDoOutput(true); urlConnection.setConnectTimeout(3000); urlConnection.setReadTimeout(3000); // 定義待寫入數據的內容類型,我們設置為application/x-www-form-urlencoded類型 urlConnection.setRequestProperty("content-type", "text/plain"); urlConnection.setRequestProperty("user-agent", "curl/7.12.1"); urlConnection.setRequestProperty("host", "data.zz.baidu.com"); urlConnection.setRequestProperty("content-length", String.valueOf(json.length()) ); // 得到請求的輸出流對象 OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream()); // 把數據寫入請求的Body out.write(json); out.flush(); out.close();
int code = urlConnection.getResponseCode();if (code != 200) {log.info("urlAddr:"+urlAddr+" code ERROR===" + code);} else {InputStream in = urlConnection.getInputStream();
br = new BufferedReader(new InputStreamReader(in, "UTF-8"));String line = "";while ((line = br.readLine()) != null)content = content + line + "\r\n";}} catch (Exception e) { e.printStackTrace();log.error("urlAddr:"+urlAddr+" post error->" + json, e);} finally { if (urlConnection!=null) urlConnection.disconnect(); if (br != null){ br.close(); }}return content;}public static String postBuiness(String urlAddr, String json) {String content = "";HttpURLConnection urlConnection = null;BufferedReader br = null;try { URL url = new URL(urlAddr); urlConnection = (HttpURLConnection) url.openConnection(); // 設置doOutput屬性為true表示將使用此urlConnection寫入數據 urlConnection.setDoOutput(true); // 定義待寫入數據的內容類型,我們設置為application/x-www-form-urlencoded類型 urlConnection.setRequestProperty("content-type", "text/plain"); urlConnection.setRequestProperty("user-agent", "curl/7.12.1"); urlConnection.setRequestProperty("host", "data.zz.baidu.com"); urlConnection.setRequestProperty("content-length", String.valueOf(json.length()) ); // 得到請求的輸出流對象 OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream()); // 把數據寫入請求的Body out.write(json); out.flush(); out.close();
int code = urlConnection.getResponseCode();if (code != 200) {log.info("ERROR===" + code);} else {InputStream in = urlConnection.getInputStream();
br = new BufferedReader(new InputStreamReader(in, "UTF-8"));String line = "";while ((line = br.readLine()) != null)content = content + line + "\r\n";}} catch (Exception e) { e.printStackTrace();log.error("urlAddr:"+urlAddr+" post error->" + json, e);} finally { if(urlConnection!=null)urlConnection.disconnect(); if (br != null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } }} return content;}
public static void main(String[] args) throws Exception {//String urlAddr = "http://api.weibo.com/2/proxy/badges/issue.json";String ak = "4CZXhoWckYANMkvlCdZNy0kjtS4Aqjqk";//params.put("source", "2067112424");//params.put("uids", "2365944120");//params.put("badge_id", "sAFStotI");Map<String, Object> headers = new HashMap<String, Object>();// HttpClient client = new HttpClient();String urlAddr = "http://10.8.2.6:9200/_analyze?pretty&analyzer=ik_smart";String result = client.post(urlAddr, "感冒的時候,最不易吃哪些東西???");System.out.println(result);}}

http 請求類