java原生API
public class HttpRequest { /** * 向指定URL發送GET方法的請求 * * @param url * 發送請求的URL * @param param * 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 * @return URL 所代表遠端資源的響應結果 */ public static String sendGet(String url, String param) { String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 開啟和URL之間的串連 URLConnection connection = realUrl.openConnection(); // 設定通用的請求屬性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立實際的串連 connection.connect(); // 擷取所有回應標頭欄位 Map<String, List<String>> map = connection.getHeaderFields(); // 遍曆所有的回應標頭欄位 for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } // 定義 BufferedReader輸入資料流來讀取URL的響應 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("發送GET請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸入資料流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } /** * 向指定 URL 發送POST方法的請求 * * @param url * 發送請求的 URL * @param param * 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 * @return 所代表遠端資源的響應結果 */ public static String sendPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; 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)"); // 發送POST請求必須設定如下兩行 conn.setDoOutput(true); conn.setDoInput(true); // 擷取URLConnection對象對應的輸出資料流 out = new PrintWriter(conn.getOutputStream()); // 發送請求參數 out.print(param); // flush輸出資料流的緩衝 out.flush(); // 定義BufferedReader輸入資料流來讀取URL的響應 in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("發送 POST 請求出現異常!"+e); e.printStackTrace(); } //使用finally塊來關閉輸出資料流、輸入資料流 finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } } catch(IOException ex){ ex.printStackTrace(); } } return result; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub //發送 GET 請求// String s=HttpRequest.sendGet("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo", "mobileCode=13069208531&userID=");// System.out.println(s); //發送 POST 請求 String sr=HttpRequest.sendPost("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo", "mobileCode=13069208531&userID="); System.out.println(sr); }}
httpclient 需要jar包:
public class HTTPUtils { private final static Logger logger = Logger.getLogger(HTTPUtils.class); private final static String OPERATER_NAME = "【HTTP操作】"; private final static int SUCCESS = 200; private final static String UTF8 = "UTF-8"; private HttpClient client; private final String respondTypeXML = "application/x-www-form-urlencoded"; private final String respondTypeJSON = "application/json;charse=UTF-8"; private static HTTPUtils instance = new HTTPUtils(); private HTTPUtils() { HttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams params = httpConnectionManager.getParams(); params.setConnectionTimeout(5000); params.setSoTimeout(20000); params.setDefaultMaxConnectionsPerHost(1000); params.setMaxTotalConnections(1000); client = new HttpClient(httpConnectionManager); client.getParams().setContentCharset(UTF8); client.getParams().setHttpElementCharset(UTF8); } public static String get(URL url) { return instance.doGet(url); } private String doGet(URL url) { long beginTime = System.currentTimeMillis(); String respStr = ""; HttpMethod method = null; try { logger.info(OPERATER_NAME + "開始get通訊,目標host:" + url); method = new GetMethod(url.toString()); // 中文轉碼 method.getParams().setContentCharset(UTF8); try { client.executeMethod(method); } catch (HttpException e) { logger.error(new StringBuffer("發送HTTP GET給\r\n").append(url) .append("\r\nHTTP異常\r\n"), e); } catch (IOException e) { logger.error(new StringBuffer("發送HTTP GET給\r\n").append(url) .append("\r\nIO異常\r\n"), e); } if (method.getStatusCode() == SUCCESS) { respStr = method.getResponseBodyAsString(); } logger.info(OPERATER_NAME + "通訊完成,返回碼:" + method.getStatusCode()); logger.info(OPERATER_NAME + "返回內容:" + method.getResponseBodyAsString()); logger.info(OPERATER_NAME + "結束..返回結果:" + respStr); } catch (Exception e) { logger.info(OPERATER_NAME, e); }finally{ if(method != null){ method.releaseConnection(); } } long endTime = System.currentTimeMillis(); logger.info(OPERATER_NAME + "共計耗時:" + (endTime - beginTime) + "ms"); return respStr; } /** * POST請求 */ public static String post(URL url, String content) { return instance.doPost(url, content); } private String doPost(URL url, String content) { long beginTime = System.currentTimeMillis(); String respStr = ""; PostMethod post = null; try { logger.info(OPERATER_NAME + "開始post通訊,目標host:" + url.toString()); logger.info("通訊內容:" + content); post = new PostMethod(url.toString()); RequestEntity requestEntity = new StringRequestEntity(content, respondTypeXML, UTF8); post.setRequestEntity(requestEntity); // 設定格式 post.getParams().setContentCharset(UTF8); client.executeMethod(post); if (post.getStatusCode() == SUCCESS) { respStr = post.getResponseBodyAsString(); } logger.info(OPERATER_NAME + "通訊完成,返回碼:" + post.getStatusCode()); logger.info(OPERATER_NAME + "返回內容:" + post.getResponseBodyAsString()); logger.info(OPERATER_NAME + "結束..返回結果:" + respStr); post.releaseConnection(); } catch (Exception e) { logger.error(OPERATER_NAME, e); }finally{ if(post != null){ post.releaseConnection(); } } long endTime = System.currentTimeMillis(); logger.info(OPERATER_NAME + "共計耗時:" + (endTime - beginTime) + "ms"); return respStr; } /** * @param args * @throws MalformedURLException */ public static void main(String[] args) throws MalformedURLException { // TODO Auto-generated method stub JSONObject json = new JSONObject(); json.put("mobileCode", "13069208531"); json.put("userID", ""); URL url = new URL("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo");// URL url = new URL("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx"// + "/getMobileCodeInfo?mobileCode=13069208531&userID="); String resp = post(url, json.toString()); //String resp = get(url); System.out.println("resp:"+resp); }}
httpclient:
public class HttpClientUtil { public static void get(String number) throws Exception{ HttpClient client = new HttpClient(); GetMethod get = new GetMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx" + "/getMobileCodeInfo?mobileCode=" + number + "&userID="); // 指定傳輸的格式為get請求格式 get.setRequestHeader("Content-Type", "text/xml; charset=utf-8"); // 發送請求 int code = client.executeMethod(get); System.out.println("Http:狀態代碼為:" + code); String result = get.getResponseBodyAsString(); System.out.println("返回的結果為:" + result); } public static void post(String number) throws Exception { //HttpClient:在java代碼中類比Http請求 // 建立瀏覽器對象 HttpClient client = new HttpClient(); // 填寫資料,發送get或者post請求 PostMethod post = new PostMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo"); // 指定傳輸的格式為預設post格式 post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // 傳輸參數 post.setParameter("mobileCode", number); post.setParameter("userID", ""); // 發送請求 int code = client.executeMethod(post); System.out.println("Http:狀態代碼為:" + code); String result = post.getResponseBodyAsString(); System.out.println("返回的結果為:" + result); } /** * @Description soap post方式請求,但是傳輸的資料為xml格式,有利於資料的維護 * @param number * @throws Exception */ //它有兩個版本soap1.1和soap1.2,jdk1.7及以上才可以使用soap1.2。 public void soap(String number) throws Exception { //HttpClient:在java代碼中類比Http請求 // 建立瀏覽器對象 HttpClient client = new HttpClient(); // 填寫資料,發送get或者post請求 PostMethod post = new PostMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx"); // 指定傳輸的格式為xml格式 post.setRequestHeader("Content-Type", "application/soap+xml;charset=utf-8"); // 傳輸xml,載入soap.txt InputStream in = HttpClientUtil.class.getClassLoader().getResourceAsStream("/soap.txt");//傳回值是一個InputStream post.setRequestBody(in); // 發送請求 int code = client.executeMethod(post); System.out.println("Http:狀態代碼為:" + code); String result = post.getResponseBodyAsString(); // 如果採用的是soap,則返回的資料也是基於xml的soap格式 System.out.println("返回的結果為:" + result); } //wsimport -s . -p com.hexy.ws http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?WSDL public static void wsdl(){ // 擷取一個ws服務 MobileCodeWS ws = new MobileCodeWS(); // 擷取具體的服務類型:get post soap1.1 soap1.2 MobileCodeWSSoap wsSoap = ws.getMobileCodeWSSoap(); String address = wsSoap.getMobileCodeInfo("18312345678", null); System.out.println("手機歸屬地資訊為:" + address); } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub post("18312345678"); //wsdl(); //soap("18312345678"); }}
soap.txt
<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> <soap12:Body> <getMobileCodeInfo xmlns="http://WebXml.com.cn/"> <mobileCode>13069208531</mobileCode> <userID></userID> </getMobileCodeInfo> </soap12:Body></soap12:Envelope>