Android
中與服務器交互主流方式與Java
後端服務器交互方式一樣,採用RESTful API +Json
的交互方式,針對不同的數據形式以及不同的解析方法。
而下面例子代碼是簡單地通過URL
與服務器交互(本質上向服務器發送請求,從服務器接收數據)。
JavaWeb的本質也是如此,前端的js代碼操作數據,發送數據給服務器,然後從服務器接收數據。
//Android與服務器通過URL交互
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
class LoginService {
static String loginByGet(String username, String password) {
try {
String path = "http://192.168.31.169:8080/AndroidClient_war_exploded/LoginServlet?username="
+ URLEncoder.encode(username, "UTF-8")
+ "&password="
+ URLEncoder.encode(password, "UTF-8");
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
int code = connection.getResponseCode();
if (code == 200) {
InputStream is = connection.getInputStream();
return StreamTools.readInputStream(is); //StreamToolsL是自己寫的類,將InputStream轉化成OutStream
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
static String loginByPost(String username, String password) {
try {
String path = "http://192.168.31.169:8080/AndroidClient_war_exploded/LoginServlet";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
String data = "username=" + URLEncoder.encode(username, "UTF-8")
+ "&password=" + URLEncoder.encode(password, "UTF-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", data.length() + "");
conn.setDoOutput(true); //setDoOutput()默認是false,需要手動設置爲true
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
return StreamTools.readInputStream(is);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
HttpURLConnection的setDoOutput()默認是false,需要手動設置爲true,完了就可以調用getOutputStream()方法從服務器端獲得字節輸出流。