HttpUrlConnection訪問Servlet進行數據傳輸


建立一個URL url = new URL("location");

建立 httpurlconnection :HttpUrlConnection httpConn = (HttpUrlConnection)url.openConnection();//強制類型轉換

String requestString = "什么gui";
設置連接屬性:
httpConn.setDoOutPut(true); //使用URL進行輸出
httpConn.setDoInPut(true); //使用URL進行輸入
httpConn.setUseCaches(false); //忽略使用緩存
httpConn.setRequestMethod("Post"); //默認情況是Get方法

設置請求屬性:
byte[] requestStringBytes = requestString.getBytes("UTF-8");
httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length);
httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
httpConn.setRequestProperty("Connection", "Keep-Alive");// 維持長連接
httpConn.setRequestProperty("Charset", "UTF-8");

建立輸出流,寫入數據:
httpConn.connect();
DataOutputStream outputStream = new DataOutputStream(httpConn.getOutputStream());
String content = "name="+ URLEncoder.encode(requestString,"utf-8");
outputStream.writeBytes(content);
outputStream.flush();
outputStream.close();

那么在Servlet端 獲取數據的方式,
String name = request.getParameter("name"); //這樣就能獲取到requestString 的字符串


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM