/*该类演示了四种方法提交数据到服务器,并将服务器解析后的数据以字符串的形式返回*/
public class LoginService {
/**
*
* @param username
* @param password
* @return
*/
public static String loginByGet(String username,String password){
try {
//提交数据到服务器
//拼装路径
String path = "http://192.168.1.100/Web/servlet/LoginServlet?username="
+ URLEncoder.encode(username,"UTF-8") + "&password=" + URLEncoder.encode(password,"UTF-8");
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();//打开连接
conn.setRequestMethod("GET");//设置请求方式为get
conn.setConnectTimeout(5000);//设置连接超时时间为5秒
int code = conn.getResponseCode();//获得请求码
if(code == 200){
InputStream is = conn.getInputStream();
String text = StreamTools.readInputStream(is);
return text;
}else{
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
* @param username
* @param password
* @return
*/
public static String loginByPost(String username,String password){
try {
//提交数据到服务器
//拼装路径
String path = "http://192.168.1.100/Web/servlet/LoginServlet";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();//打开连接
conn.setRequestMethod("POST");//设置请求方式为get
conn.setConnectTimeout(5000);//设置连接超时时间为5秒
//准备数据
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()+"");
//post的方
Android 提交数据到服务器的四种方法
最新推荐文章于 2021-05-26 00:51:17 发布
本文介绍了Android应用中向服务器提交数据的四种常见方法,包括使用HTTP请求库、JSON解析、文件上传以及同步与异步策略。通过实例代码详细解析了如何实现数据的高效安全传输。
摘要由CSDN通过智能技术生成