您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關HttpURLConnection怎么在Java項目中使用,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
包括使用HttpURLConnection執行get/post請求
package com.cn.testproject; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpConnectionUrlDemo { public static void main(String[] args) throws Exception { //get(); post(); } public static void get() throws Exception { String path = "http://www.baidu.com"; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod("GET"); InputStream inStream = conn.getInputStream(); byte[] data = toByteArray(inStream); String result = new String(data, "UTF-8"); System.out.println(result); } public static void post() throws Exception { String encoding = "UTF-8"; //post的form參數(json兼職對) String params = "[{\"addTime\":\"2011-09-19 14:23:02\"[],\"iccid\":\"1111\",\"id\":0,\"imei\":\"2222\",\"imsi\":\"3333\",\"phoneType\":\"4444\",\"remark\":\"aaaa\",\"tel\":\"5555\"}]"; String path = "http://www.baidu.com"; byte[] data = params.getBytes(encoding); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-javascript; charset=" + encoding); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); conn.setConnectTimeout(5 * 1000); OutputStream outStream = conn.getOutputStream(); outStream.write(data); outStream.flush(); outStream.close(); System.out.println(conn.getResponseCode()); // 響應代碼 200表示成功 if (conn.getResponseCode() == 200) { InputStream inStream = conn.getInputStream(); String result = new String(toByteArray(inStream), "UTF-8"); System.out.println(result); // 響應代碼 200表示成功 } } private static byte[] toByteArray(InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } return output.toByteArray(); } }
關于HttpURLConnection怎么在Java項目中使用就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。