客戶端代碼示例:web
public static void main(String[] args) {
String urlPath = "http://localhost:8080/web1/servletTestCallBack.hts";
try {
String param = "name=" + URLEncoder.encode("測試","UTF-8");
//創建鏈接
URL url = new URL(urlPath + "?" + param);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setDoOutput(true); // 須要輸出
httpConn.setDoInput(true); // 須要輸入
httpConn.setUseCaches(false); // 不容許緩存
httpConn.setRequestMethod("GET"); //設置GET方式鏈接
//設置請求屬性
httpConn.setRequestProperty("Content-Type", "text/plain"); //表單提交 "application/x-www-form-urlencoded"
httpConn.setRequestProperty("Connection", "Keep-Alive"); // 維持長鏈接
httpConn.setRequestProperty("Charset", "UTF-8"); // 字符編碼
httpConn.setConnectTimeout(5*1000); // 設置鏈接服務器超時時間
httpConn.setReadTimeout(5*1000); // 設置從主機讀取數據超時(單位:毫秒)
httpConn.connect(); //鏈接
//得到響應狀態
int resultCode = httpConn.getResponseCode();
if(HttpURLConnection.HTTP_OK == resultCode){
StringBuffer sb = new StringBuffer();
String readLine = new String();
BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
while((readLine = responseReader.readLine())!=null){
sb.append(readLine).append("\n");
}
responseReader.close();
System.out.println("響應數據:"+sb.toString());
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}數組
}緩存
服務器端代碼示例:服務器
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {app
request.setCharacterEncoding("UTF-8");
//獲得客戶端發送過來內容的類型
System.out.println("客戶端發送過來內容的類型:" + request.getContentType());
String name = request.getParameter("name");
//獲取request對象以ISO8859-1字符編碼接收到的原始數據的字節數組,而後經過字節數組以指定的編碼構建字符串,解決亂碼問題。
name = new String(name.getBytes("ISO8859-1"),"UTF-8");
System.out.println("客戶端傳遞的參數name:" + name);
//響應客戶端
response.setCharacterEncoding("UTF-8");
response.getWriter().print("接受到信息,ok!");
}ide
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}測試