因為某些原因,需要類比Http post,向伺服器進行提交資料。自己琢磨了很多種方法,什麼ajax類比,什麼注入啊,想想都太進階了,自己也不太懂,於是想了想,咱也是java程式員,還是找個java的,這樣應用起來也是得心應手了。於是施展了baidu和google大法,直接找到了一個開箱即用的類比方法。我進行了簡單的修改。具體代碼如下:
1 public class HttpPostSimulator { 2 public static void post() throws IOException { 3 4 URL url = new URL("http://a.b.com/dda/updateCCC.action"); 5 URLConnection connection = url.openConnection(); 6 connection.setDoOutput(true); 7 OutputStreamWriter out = new OutputStreamWriter( 8 connection.getOutputStream(), "utf-8"); 9 10 // post的資料11 out.write("s.code=de0947&s.typeCode=ccc"); 12 // 向頁面傳遞資料。post的關鍵所在!13 out.flush();14 out.close();15 16 // 一旦發送成功,用以下方法就可以得到伺服器的回應:17 String sCurrentLine;18 String sTotalString;19 sCurrentLine = "";20 sTotalString = "";21 // 傳說中的三層封裝阿!22 BufferedReader resultReader = new BufferedReader(new InputStreamReader(23 connection.getInputStream()));24 while ((sCurrentLine = resultReader.readLine()) != null) {25 sTotalString += sCurrentLine + "\r\n";26 27 }28 System.out.println(sTotalString);29 30 }31 32 public static void main(String[] args) throws IOException {33 post();34 }35 }
參考的地址:
Java類比Post 提交表單資料
http://blog.csdn.net/kalision/article/details/7920908