第二部分android客户端的建立
首先我们先定义一个http的工具类HttpUtils
package com.example.android_httppost_login.http;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.R.integer;
import android.util.Log;
public class HttpUtils {
public HttpUtils(){
}
public static String sendPostMenthod(String path,
Map<String , Object> params,String encoding){
<span style="white-space:pre"> </span>//path是上篇文章的web服务地址,params是封装好你要查询的用户的信息,encoding是采用的编码格式
String result="";
HttpClient httpClient=new DefaultHttpClient();
HttpPost post=new HttpPost(path);
List<BasicNameValuePair> parameters=new ArrayList<BasicNameValuePair>();
try {
if(params!=null&&!params.isEmpty()){
for(Map.Entry<String, Object> entry:params.entrySet()){
String name=entry.getKey();
String value=entry.getValue().toString();
BasicNameValuePair valuePair=new BasicNameValuePair(name, value);
parameters.add(valuePair);
<span style="white-space:pre"> </span>//这里完成了表单的封装,把传过来的params表单封装成了parameters表单
}
}
//纯文本提交不包含文件的提交,UrlEncodedFormEntity为要提交的表单
UrlEncodedFormEntity encodedFormEntity=new UrlEncodedFormEntity(parameters, encoding);
post.setEntity(encodedFormEntity);//为post设置提交的表单
HttpResponse response=httpClient.execute(post);//httpClient提交定义好的post方法,并返回结果response表单
if(response.getStatusLine().getStatusCode()==200){
result=EntityUtils.toString(response.getEntity(),
encoding);//把response表单转换成String
}else{
System.out.println("tab"+ "连接失败");
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return result;
}
}
<span style="font-size:18px; font-family: Arial, Helvetica, sans-serif;">这里的ResultMessage同服务器端的一模一样可以复制过来</span>
package com.example.android_httppost_login.domin;
public class ResultMessage {
private int resultCode;//结果码
private String resultMsaaage;//结果信息
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
public String getResultMsaaage() {
return resultMsaaage;
}
public void setResultMsaaage(String resultMsaaage) {
this.resultMsaaage = resultMsaaage;
}
public ResultMessage() {
// TODO Auto-generated constructor stub
}
public ResultMessage(int resultCode, String resultMsaaage) {
super();
this.resultCode = resultCode;
this.resultMsaaage = resultMsaaage;
}
}
好了最后在服务器端传过来的字符串是json字符串,我们解析一下就ok了。
我们定义一个jsontool工具类
<pre name="code" class="java">package com.example.android_httppost_login.json;
import org.json.JSONObject;
import com.example.android_httppost_login.domin.ResultMessage;
public class Jsontools {//json的解析工具,最后返回一个ResultMessage类的结果对象
public static ResultMessage getResultMessage(String josnString){
ResultMessage message=null;
try {
JSONObject rootJsonObject=new JSONObject(josnString);
JSONObject jsonObject=rootJsonObject.getJSONObject("result");
message=new ResultMessage();
message.setResultCode(jsonObject.getInt("resultCode"));
message.setResultMsaaage(jsonObject.getString("resultMessage"));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return message;
}
}
最后就是要写进MainActivity了,记得要加网络授权呀
<pre name="code" class="java">package com.example.android_httppost_login;
import java.util.HashMap;
import java.util.Map;
import com.example.android_httppost_login.domin.ResultMessage;
import com.example.android_httppost_login.http.HttpUtils;
import com.example.android_httppost_login.json.Jsontools;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity {
public Button button1;
public Button button2;
public EditText nametest;
public EditText passtest;
private final String LOGIN_PATH="http://10.0.2.2:8080/myweb/servlet/LoginAction";
<span style="white-space:pre"> </span>/*这里要重点说明一下,因为我在这试了一下午的时间,快烦死我了。ip一定要写10.0.2.2不能写localhost或者127.0.0.1,因为在虚拟机中localhost默认你要访问虚拟机本身而不是你的电脑,你电脑的ip被映射为10.0.2.2。*/
<span style="white-space:pre"> </span>//因为这是一个耗时操作,所以不予许在主线程里进行,所以会定义一个异步任务类
<span style="white-space:pre"> private ProgressDialog dialog;</span>
<span style="white-space:pre"> @Override</span>
<span style="white-space:pre"> protected void onCreate(Bundle savedInstanceState) {</span>
<span style="white-space:pre"> super.onCreate(savedInstanceState);</span>
<span style="white-space:pre"> setContentView(R.layout.activity_main);</span>
<span style="white-space:pre"> dialog=new ProgressDialog(this);dialog.setTitle("提示");</span>
<span style="white-space:pre"> dialog.setMessage("正在登陆请稍候。。。。。");</span>
<span style="white-space:pre"> button1=(Button)findViewById(R.id.button1);</span>
<span style="white-space:pre"> button2=(Button)findViewById(R.id.button2);</span>
<span style="white-space:pre"> nametest=(EditText)findViewById(R.id.editText1);</span>
<span style="white-space:pre"> passtest=(EditText)findViewById(R.id.editText2);</span>
<span style="white-space:pre"> button1.setOnClickListener(new View.OnClickListener() {</span>
<span style="white-space:pre"> @Overrid</span>
<span style="white-space:pre"> epublic void onClick(View v) {</span>
<span style="white-space:pre"> String name_value=nametest.getText().toString().trim();</span>
<span style="white-space:pre"> String pswd_value=passtest.getText().toString().trim();</span>
<span style="white-space:pre"> Map<String, String> params=new HashMap<String, String>();</span>
<span style="white-space:pre"> //把你查询的数据封装成表单</span>
<span style="white-space:pre"> params.put("url",LOGIN_PATH);</span>
<span style="white-space:pre"> params.put("username", name_value);</span>
<span style="white-space:pre"> params.put("password", pswd_value);</span>
<span style="white-space:pre"> try {</span>
String result=new LoginAsyncTask().execute(params).get();
ResultMessage message=Jsontools.getResultMessage(result);//获取结果码
if(message.getResultCode()==1){//1是登陆成功的结果码
Toast.makeText(MainActivity.this,
message.getResultMsaaage(), 1).show();
}
else{Toast.makeText(MainActivity.this,
"登录失败", 1).show();}
} catch (Exception e) {
// TODO: handle exception
}
}
});
}
//异步任务的内容可以参考我后面的文章
class LoginAsyncTask extends AsyncTask<Map<String, String>, Void, String>{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.show();
}
@Override
protected String doInBackground(Map<String, String>... params) {
// TODO Auto-generated method stub
Map<String,String> map=params[0];
//将要传递的表单数据
Map<String,Object> params2=new HashMap<String, Object>();
params2.put("username", map.get("username"));
params2.put("password", map.get("password"));
String result=HttpUtils.sendPostMenthod(map.get("url"), params2, "utf-8");
return result;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
}
}
//下面是系统自带的代码
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
<span style="font-size:18px;">ok到这里节结束了,点击运行吧,祝你好运,如果不成功也不要放弃,多试几次总会成功的。。</span>
<span style="font-size:18px;">json包下载地址<a target=_blank href="http://download.csdn.net/detail/california94/9272585" target="_blank">点击打开链接</a>,记得把它引入到你的工程,还有连接数据库的包都要引入。</span>