老羅視頻學習。
本例從客戶端提交數據給服務器,服務器接收到數據之後,看是否匹配,匹配返回字符串“login is success!”,失敗返回“login is error!”
一.客戶端。
初始化url地址
private static String path = "http://192.168.10.102:8080/myhttp/servlet/LoginActivity";
private static URL url;
static{
try {
url = new URL(path);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
setPostMessage函數
getOutputStream是向服務器傳遞數據用的。
getInputStream是從服務器獲取數據用的。
向服務器輸入數據傳遞圖片之類的,要用HttpUrlConnection類
doInput默認值是true,doOutput默認值是false。
private static String sendPostMessage(Map<String, String> params,String encode) {
//請求體封裝在StringBuffer中
StringBuffer buffer = new StringBuffer();
//buffer.append("?");
try {
//判斷是否爲空
if(params!=null && !params.isEmpty()){
//迭代for循環
for(Map.Entry<String, String> entry : params.entrySet()){
//append,追加字符串
buffer.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(),encode))
.append("&");
}
}
//刪掉最後多餘的那個“&”
buffer.deleteCharAt(buffer.length()-1);
System.out.print(buffer.toString());
//接下來是http協議內容
//打開鏈接
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//設置服務器斷開重連時間
urlConnection.setConnectTimeout(3000);
//設置提交方式
urlConnection.setRequestMethod("POST");
//設置從服務器讀取數據
urlConnection.setDoInput(true);
//設置向服務器寫數據
urlConnection.setDoOutput(true);
//接下來需要把url的請求的內容,封裝到一個請求體中
//獲得上傳信息的字節大小
byte[] data = buffer.toString().getBytes();
//設置請求體的類型
//設置請求體類型爲文本類型,暫時不涉及圖片及二進制數據
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//設置請求體的長度
urlConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
//獲得輸出流,向服務器輸出數據
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(data,0,data.length);
outputStream.close();
//獲得服務器響應的結果和狀態碼
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
//把inputStream改爲String傳遞出來
return ChangeInputStream(urlConnection.getInputStream(),encode);
}
}catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return path;
}
changeInputStream函數如下:
把InputStream以encode格式轉換爲String
private static String ChangeInputStream(InputStream inputStream,
String encode) {
// TODO Auto-generated method stub
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
String resultString = "";
if(inputStream!=null) {
try {
//數據循環存儲在outputStream中
while ((len=inputStream.read(data))!=-1) {
outputStream.write(data,0,len);
}
//首先轉換爲字節數組,然後以encode編碼格式轉換爲字符串
resultString = new String(outputStream.toByteArray(),encode);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
測試main函數如下:
public static void main(String[] args) {
Map<String, String> params = new HashMap<String, String>();
params.put("username", "admin");
params.put("password", "123");
String encode = "utf-8";
String resString = HttpUrils.sendPostMessage(params, encode);
System.out.print("------>"+resString);
}
二.服務器端,還用get方式例子裏用到的服務器。
LoginActivity繼承自HttpServlet
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
//設置編碼格式
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//獲取用戶名username,密碼password
PrintWriter out = resp.getWriter();
String usernameString = req.getParameter("username");
String pswdString = req.getParameter("password");
System.out.print(usernameString);
System.out.print(pswdString);
//匹配成功
if(usernameString.equals("admin")&&pswdString.equals("123")){
out.print("login is success!");
}//匹配不成功
else {
out.print("login is error!");
}
out.flush();
out.close();