Android 采用post方式提交数据到服务器
接着上篇《Android 采用get方式提交数据到服务器》,本文来实现采用post方式提交数据到服务器
首先对比一下get方式和post方式:

修改布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" > <EditText
android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名"
android:inputType="text" /> <EditText
android:id="@+id/et_pwd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"
android:inputType="textPassword" />
<Button
android:onClick="LoginByGet"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="GET方式登录"
/>
<Button
android:onClick="LoginByPost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="POST方式登录"
/> </LinearLayout>
添加代码:
package com.wuyudong.loginclient; import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL; import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast; public class MainActivity extends Activity {
private EditText et_name;
private EditText et_pwd; protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); et_name = (EditText) findViewById(R.id.et_name);
et_pwd = (EditText) findViewById(R.id.et_pwd); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy); } public void LoginByGet(View view) { String name = et_name.getText().toString().trim();
String pwd = et_pwd.getText().toString().trim(); if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)) {
Toast.makeText(this, "用户名密码不能为空", 0).show();
} else {
// 模拟http请求,提交数据到服务器
String path = "http://169.254.168.71:8080/web/LoginServlet?username="
+ name + "&password=" + pwd;
try {
URL url = new URL(path);
// 2.建立一个http连接
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
// 3.设置一些请求方式
conn.setRequestMethod("GET");// 注意GET单词字幕一定要大写
conn.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"); int code = conn.getResponseCode(); // 服务器的响应码 200 OK //404 页面找不到
// // 503服务器内部错误
if (code == 200) {
InputStream is = conn.getInputStream();
// 把is的内容转换为字符串
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
String result = new String(bos.toByteArray());
is.close();
Toast.makeText(this, result, 0).show(); } else {
Toast.makeText(this, "请求失败,失败原因: " + code, 0).show();
} } catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "请求失败,请检查logcat日志控制台", 0).show();
} } } /**
* 采用post的方式提交数据到服务器
*
* @param view
*/
public void LoginByPost(View view) {
String name = et_name.getText().toString().trim();
String pwd = et_pwd.getText().toString().trim(); if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)) {
Toast.makeText(this, "用户名密码不能为空", 0).show();
} else {
try {
String path = "http://169.254.168.71:8080/web/LoginServlet?username="
+ name + "&password=" + pwd;
// 1.定义请求url
URL url = new URL(path);
// 2.建立一个http的连接
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
// 3.设置一些请求的参数
conn.setRequestMethod("POST");
conn.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
String data = "username=" + name + "&password=" + pwd;
conn.setRequestProperty("Content-Length", data.length() + "");
conn.setConnectTimeout(5000);//设置连接超时时间
conn.setReadTimeout(5000); //设置读取的超时时间 // 4.一定要记得设置 把数据以流的方式写给服务器
conn.setDoOutput(true); // 设置要向服务器写数据
conn.getOutputStream().write(data.getBytes()); int code = conn.getResponseCode(); // 服务器的响应码 200 OK //404 页面找不到
// // 503服务器内部错误
if (code == 200) {
InputStream is = conn.getInputStream();
// 把is的内容转换为字符串
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
String result = new String(bos.toByteArray());
is.close();
Toast.makeText(this, result, 0).show(); } else {
Toast.makeText(this, "请求失败,失败原因: " + code, 0).show();
} } catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "请求失败,请检查logcat日志控制台", 0).show();
}
} }
}
Android 采用post方式提交数据到服务器的更多相关文章
- Android 采用get方式提交数据到服务器
首先搭建模拟web 服务器,新建动态web项目,servlet代码如下: package com.wuyudong.web; import java.io.IOException; import ja ...
- 采用get方式提交数据到服务器实例
GetDemo项目目录 一.编写StreamTools.java /** * */ package com.hyzhou.getdemo.utiils; import java.io.ByteArra ...
- Android(java)学习笔记210:采用post请求提交数据到服务器(qq登录案例)
1.POST请求: 数据是以流的方式写给服务器 优点:(1)比较安全 (2)长度不限制 缺点:编写代码比较麻烦 2.我们首先在电脑模拟下POST请求访问服务器的场景: 我们修改之前编写的logi ...
- Android(java)学习笔记153:采用post请求提交数据到服务器(qq登录案例)
1.POST请求: 数据是以流的方式写给服务器 优点:(1)比较安全 (2)长度不限制 缺点:编写代码比较麻烦 2.我们首先在电脑模拟下POST请求访问服务器的场景: 我们修改之前编写的logi ...
- Android 使用Post方式提交数据
在Android中,提供了标准Java接口HttpURLConnection和Apache接口HttpClient,为客户端HTTP编程提供了丰富的支持. 在HTTP通信中使用最多的就是GET和POS ...
- Android 使用Post方式提交数据(登录)
在Android中,提供了标准Java接口HttpURLConnection和Apache接口HttpClient,为客户端HTTP编程提供了丰富的支持. 在HTTP通信中使用最多的就是GET和POS ...
- Android(java)学习笔记209:采用get请求提交数据到服务器(qq登录案例)
1.GET请求: 组拼url的路径,把提交的数据拼装url的后面,提交给服务器. 缺点:(1)安全性(Android下提交数据组拼隐藏在代码中,不存在安全问题) (2)长度有限不能超过4K(h ...
- Android(java)学习笔记152:采用get请求提交数据到服务器(qq登录案例)
1.GET请求: 组拼url的路径,把提交的数据拼装url的后面,提交给服务器. 缺点:(1)安全性(Android下提交数据组拼隐藏在代码中,不存在安全问题) (2)长度有限不能超过4K(h ...
- httpclient方式提交数据到服务器
get方式: //使用HttpClient请求服务器将用户密码发送服务器验证 try{ String path = "http://192.168.13.83:8080/xuexi/serv ...
随机推荐
- 定义通用的可通过lambda表达式树来获取属性信息
我们一般获取某个类型或对象的属性信息均采用以下几种方法: 一.通过类型来获取属性信息 var p= typeof(People).GetProperty("Age");//获取指定 ...
- When using SqlDependency without providing an options value, SqlDependency.Start() must be called prior to execution of a command added to the SqlDependency instance.
在调试SignalR程序时,提示一个异常:When using SqlDependency without providing an options value, SqlDependency.Star ...
- Rebalance Customer Balances Utility的使用
用户不管是打开A/R Posted Transactions Detail还是A/R Posted Transactions Summary 窗口,均显示如下一个警示: 打开Currency Code ...
- DevExpress的XtraReport和微软RDLC报表的使用和对比
我们开发程序的时候,经常会碰到一些报表,如果是Winform的报表,一般可以采用DevExpress控件组的XtraReport,或者微软的RDLC报表,当然还有一些其他的,在此不再赘述.由于本人在W ...
- PHP面试题汇总
1.用PHP打印出前一天的时间格式是2014-01-13 12:10:21(2分) 2.echo(),print(),print_r()的区别(3分) 3.能够使HTML和PHP分离开使用的模板(1分 ...
- javascript常用判断写法
js验证表单大全,用JS控制表单提交 ,javascript提交表单 目录:1:js 字符串长度限制.判断字符长度 .js限制输入.限制不能输入.textarea 长度限制 2.:js判断汉字.判断是 ...
- OS初识
参考: 操作系统的故事(1-4):
- x8086汇编实现dos清屏(clear screen)
题目要求:x8086汇编实现dos下的清屏功能 80X25彩色字符模式显示缓冲区的结构: 在内存地址结构中,B8000H~BFFFFH共32KB的空间,为80x25彩色字符模式的显示缓冲区.向这个地址 ...
- Java分布式开发
分布式概念的引入是基于性能的提升,应用的可靠性而提出的.所谓Java分布式,即是在使用Java语言进行企业级应用开发的过程中,采用分布式技术解决业务逻辑的高并发.高可用性的一些架构设计方案. 1. R ...
- JAVA开发环境和IntelliJ工具安装
在本地开发机中进行web项目的开发,部署到生产环境进行产品发布时,需要将web应用的文件打包成war包,War包可以放在Tomcat下的webapps或者word目录下,随着tomcat服务器的启动, ...