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()方法从服务器端获得字节输出流。