Http訪問網路之GET和POST,訪問getpost
public class HttpGetUtil {// 用get請求擷取輸入資料流public static InputStream getInputStream() {InputStream inputStream = null;HttpURLConnection httpURLConnection = null;try {URL url = new URL("http://www.baidu.com/img/bd_logo1.png");if (url != null) {httpURLConnection = (HttpURLConnection) url.openConnection();// 設定串連網路的逾時時間httpURLConnection.setConnectTimeout(3000);// 開啟輸入資料流httpURLConnection.setDoInput(true);// 使用GET方法請求httpURLConnection.setRequestMethod("GET");// 擷取結果響應碼int responseCode = httpURLConnection.getResponseCode();if (responseCode == 200) {inputStream = httpURLConnection.getInputStream();}}} catch (Exception e) {e.printStackTrace();}return inputStream;}// 將輸入資料流存在本地public void saveImageToDisk() {InputStream inputStream = getInputStream();byte[] data = new byte[1024];int len = 0;FileOutputStream fileOutputStream = null;try {fileOutputStream = new FileOutputStream("D://test.png");while ((len = inputStream.read(data)) != -1) {fileOutputStream.write(data, 0, len);}} catch (Exception e) {e.printStackTrace();} finally {if (inputStream != null) {try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}}}}
public class HttpPostUtil {private static URL url;// 用post請求擷取輸入資料流public static String sendPostMessage(Map<String, String> params, String encode) {// 初始化StringBuffer buffer = new StringBuffer();buffer.append("?");try {if (params != null && !params.isEmpty()) {for (Map.Entry<String, String> entry : params.entrySet()) {// 完成轉碼buffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), encode)).append("&");}// 刪掉最後一個&buffer.deleteCharAt(buffer.length() - 1);}HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();urlConnection.setConnectTimeout(3000);urlConnection.setRequestMethod("POST");urlConnection.setDoInput(true);// 從伺服器擷取資料urlConnection.setDoOutput(true);// 向伺服器寫資料// 獲得上傳資訊的位元組大小以及長度byte[] mydata = buffer.toString().getBytes();// 表示佈建要求體的類型是文本類型urlConnection.setRequestProperty("Content-type", "application/x-www-from-urlencoded");urlConnection.setRequestProperty("Content-length", String.valueOf(mydata.length));// 獲得輸出資料流,向伺服器輸出資料OutputStream outputStream = urlConnection.getOutputStream();outputStream.write(mydata, 0, mydata.length);outputStream.close();int responseCode = urlConnection.getResponseCode();if (responseCode == 200) {return changeInputStream(urlConnection.getInputStream(), encode);}} catch (Exception e) {e.printStackTrace();}return "";}// 將一個輸入資料流轉化成字串private static String changeInputStream(InputStream inputStream, String encode) {ByteArrayOutputStream outputStream = new ByteArrayOutputStream();byte[] data = new byte[1024];int len = 0;String result = "";if (inputStream != null) {try {while ((len = inputStream.read()) != -1) {outputStream.write(data, 0, len);}result = new String(outputStream.toByteArray(), encode);} catch (Exception e) {e.printStackTrace();}}return result;}}