Android 提交数据到服务器的四种方法

本文介绍了Android应用中向服务器提交数据的四种常见方法,包括使用HTTP请求库、JSON解析、文件上传以及同步与异步策略。通过实例代码详细解析了如何实现数据的高效安全传输。
摘要由CSDN通过智能技术生成
/*该类演示了四种方法提交数据到服务器,并将服务器解析后的数据以字符串的形式返回*/
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的方
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值