【Android学习笔记--Http协议】卧疾丰暇豫,翰墨时间作。这篇文章主要讲述Android学习笔记--Http协议相关的知识,希望能为你提供帮助。
HttpURLConnection 分别有GET和POST请求
Post方式的
1public void testPOstbendi() throws Exception { 2//构建服务器地址 3URL url = new URL("http://192.168.40.194/qiantai/admin/login_check.php"); 4//获取HttpURLConnection对象 5HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 6//设置请求时间 7httpURLConnection.setReadTimeout(10000); 8httpURLConnection.setConnectTimeout(10000); 9//设置方式 10httpURLConnection.setRequestMethod("POST"); 11//建立一个实际的链接 12httpURLConnection.connect(); 13//获取输出流 14OutputStream os = httpURLConnection.getOutputStream(); 15//POST提交的字段 16String message ="username=admin& userpass=123456"; 17//想服务器写入数据 18os.write(message.getBytes()); 19//获取服务端返回的状态码 20int code = httpURLConnection.getResponseCode(); 21//switch判断一下 22switch (code){ 23case 201: 24case 200: 25//获取服务器返回的输入流 26InputStream inputStream = httpURLConnection.getInputStream(); 27StringBuffer stringBuffer = new StringBuffer(); 28String strings; 29//转换成字符输入流 30BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 31while ((strings = bufferedReader.readLine())!= null){ 32stringBuffer.append(strings); 33} 34//关闭数据链接 35httpURLConnection.disconnect(); 36Log.e(TAG, "testURl: "+stringBuffer.toString()); 37break; 38case 401: 39Log.e(TAG, "tes401了啊=========================================================="); 40break; 41} 42}
GET方式的
public void testURl() throws Exception { //构建URL URL url = new URL("http://life.tenpay.com/cgi-bin/mobile/MobileQueryAttribution.cgi?chgmobile=15850781443"); //获取httpURLConnection HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); //设置超市时间 httpURLConnection.setConnectTimeout(10000); httpURLConnection.setReadTimeout(10000); //设置请求方式 httpURLConnection.setRequestMethod("GET"); //获取请求码 int code = httpURLConnection.getResponseCode(); switch (code){ case 200: InputStream inputStream = httpURLConnection.getInputStream(); StringBuffer sb = new StringBuffer(); String str; BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); while ((str = reader.readLine()) != null){ sb.append(str+"\n"); } Log.e(TAG, "testURl: "+sb.toString()); break; case 401: Log.e(TAG, "testURl: 401"); break; } }
推荐阅读
- Android AIDL 小结
- android 安卓editext默认弹出英文输入法,只能输入英文与数字
- android 安卓edittext自动弹出数字键盘
- android安卓editText自动弹出软键盘(输入键盘)
- Android热修复——Tinker微信解决方案
- Android的热修复-微信Tinker
- Android 集成支付宝支付详解
- android 图像的一些操作处理
- 关于Android6.0之后的权限问题