前几次研究了Android端怎样解析web端上传的网络数据,这次我们来一起研究研究Android网络数据之向服务器提交数据的三种方式(get+post+AsyncHttpClient)
首先先来看看Android端的测试页面截图:(两个编辑框,分别为用户名和密码框,如若输入的的用户名密码是admin 123 的话,就会吐司success,否则就会吐司fail,三种方式,分别为三个按钮,也就是三个onclick事件)
我们先在web端写一个登录页面,以及登录方法:(SSH框架)
LoginAction.class:
public class LoginAction extends ActionSupport{
private String uname;
private String upass;
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpass() {
return upass;
}
public void setUpass(String upass) {
this.upass = upass;
}
public String login() throws Exception {
System.out.println("uname="+uname+" upass="+upass);
String result=null;
//判断数据库
if("admin".equals(uname)&&"123456".equals(upass)){
result="success";
}else{
result="fail";
}
ServletActionContext.getRequest().setAttribute("result", result);
return "loginResult";
}
}
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="loginActionlogin.action" method="post">
Uname:<input type="text" name="uname"/><br/>
Upass:<input type="text" name="upass"/><br/>
<input type="submit" value="登录"/><br/>
</form>
</body>
</html>
loginresult.jsp
<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8"%>${result}
struts.xml
<action name="loginAction*" class="com.zking.action.LoginAction" method="{1}">
<result name="loginResult">/loginResult.jsp</result>
</action>
web端的页面准备好了,现在我们来Android端提交数据
main.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="admin"
android:id="@+id/et_main_uname"
/>
<EditText
android:id="@+id/et_main_upass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="123456" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="loginByGet"
android:text="登录(GET)" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="loginByPost"
android:text="登录(POST)" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="loginByAsyncHttpClient"
android:text="登录(AsyncHttpClient)" />
main.activiy:
public class MainActivity extends AppCompatActivity {
private EditText et_main_uname;
private EditText et_main_upass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_main_uname = (EditText) findViewById(R.id.et_main_uname);
et_main_upass = (EditText) findViewById(R.id.et_main_upass);
}
public void loginByGet(View view) {
String uname = et_main_uname.getText().toString();
String upass = et_main_upass.getText().toString();
String path = getString(R.string.server_name) + "loginActionlogin.action";
//可变数组
new MyTask().execute(uname, upass, path, "GET");
}
public void loginByPost(View view) {
String uname = et_main_uname.getText().toString();
String upass = et_main_upass.getText().toString();
String path = getString(R.string.server_name) + "loginActionlogin.action";
//可变数组
new MyTask().execute(uname, upass, path, "POST");
}
public void loginByAsyncHttpClient(View view) {
String uname = et_main_uname.getText().toString();
String upass = et_main_upass.getText().toString();
String path = getString(R.string.server_name) + "loginActionlogin.action";
AsyncHttpClient asyncHttpClient=new AsyncHttpClient();
RequestParams requestParams=new RequestParams();
requestParams.put("uname",uname);
requestParams.put("upass",upass);
asyncHttpClient.post(path,requestParams,new TextHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, String responseBody) {
super.onSuccess(statusCode, headers, responseBody);
Toast.makeText(MainActivity.this, responseBody, Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable error) {
super.onFailure(statusCode, headers, responseBody, error);
}
});
}
class MyTask extends AsyncTask {
private HttpURLConnection connection;
private URL url;
@Override
protected Object doInBackground(Object[] objects) {
//获取参数的值
String uname = objects[0].toString();
String upass = objects[1].toString();
String path = objects[2].toString();
String type = objects[3].toString();
String str="uname="+uname+"&upass="+upass;
try {
if ("GET".equals(type)) {
//用GET方式提交
path = path + "?"+str;
url = new URL(path);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(type);
} else if ("POST".equals(type)) {
//用POST方式提交
url = new URL(path);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(type);
//设置contentType contentLength
connection.setRequestProperty("Content-Length",str.length()+"");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
//设置允许对外输出数据
connection.setDoOutput(true);
//将用户名和密码提交到服务器
connection.getOutputStream().write(str.getBytes());
}
connection.setConnectTimeout(5000);
if (connection.getResponseCode() == 200) {
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String result = br.readLine();
return result;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
String s = (String) o;
Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
}
}
}
在这里,我将三种提交数据方式共同使用一个AsynTask,减少了重复的代码,但是注意,有些代码在不同的提交方式判断里面是不能够删掉的,比如:
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(type);