標籤:
GET請求
/** * 從網路擷取json資料,(String byte[})
* @param path * @return */ public static String getJsonByInternet(String path){ try { URL url = new URL(path.trim()); //開啟串連 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); if(200 == urlConnection.getResponseCode()){ //得到輸入資料流 InputStream is =urlConnection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while(-1 != (len = is.read(buffer))){ baos.write(buffer,0,len); baos.flush(); } return baos.toString("utf-8"); } } catch (IOException e) { e.printStackTrace(); } return null; }
POST請求
//擷取其他頁面的資料 /** * POST請求擷取資料 */ public static String postDownloadJson(String path,String post){ URL url = null; try { url = new URL(path); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST");// 提交模式 // conn.setConnectTimeout(10000);//連線逾時 單位毫秒 // conn.setReadTimeout(2000);//讀取逾時 單位毫秒 // 發送POST請求必須設定如下兩行 httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); // 擷取URLConnection對象對應的輸出資料流 PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream()); // 發送請求參數 printWriter.write(post);//post的參數 xx=xx&yy=yy // flush輸出資料流的緩衝 printWriter.flush(); //開始擷取資料 BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int len; byte[] arr = new byte[1024]; while((len=bis.read(arr))!= -1){ bos.write(arr,0,len); bos.flush(); } bos.close(); return bos.toString("utf-8"); } catch (Exception e) { e.printStackTrace(); } return null; }
httpURLConnection-網路請求的兩種方式-get請求和post請求