Android手机访问web服务器(post请求)

来源:互联网 发布:cg绘画软件 编辑:程序博客网 时间:2024/04/30 20:26

一:客户端—服务器连接操作类(HttpUtil)

package com.example.userdatatoweb;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
 * Android客户端连接服务器操作类
 * */
public class HttpUtil {
 
 public static String serverPath="222.23.162.221:8080";                                                                    

//服务器的ip地址以及参数
 public static String contextPath="/prjMyschoolmate";                                                                        

//服务器虚拟目录(web项目名),研究web服务器上下文路径
 public static String loginUrl="
http://"+serverPath+contextPath+"/servlet/LoginServlet";                    

//服务器的登录的url
 public static String allUser="
http://"+serverPath+contextPath+"/servlet/GetAllStudentServlet";       

//获取服务器中所有的学生信息
 public static String userDetails="
http://"+serverPath+contextPath+"/servlet/GetStudentById";        

//根据id查询学生的详细信息
 public static String deleteUser="
http://"+serverPath+contextPath+"/servlet/DeleteStudent";           

//根据id删除学生信息
 public static String addUser="
http://"+serverPath+contextPath+"/servlet/AddStudent";                   

//保存学生信息
 public static String updateUser="
http://"+serverPath+contextPath+"/servlet/UpdateStudent";        

//更新学生信息
 
 /**
  * 发送请求,并获取相应,用post访问服务器
  * @param url 请求地址
  * @param map 请求参数
  * @throws Exception
  * */
 public static String sendRequest(String url,Map<String, String> map) throws Exception{
  
  String msg="";
  String urlstr=url;
  

  //准备post请求对象
  HttpPost request=new HttpPost(urlstr);
  List<NameValuePair> params=new ArrayList<NameValuePair>();
  //这个内容:把map中的键值对,存放到params对象中,该对象是一个List集合,内容为NameValuePair对象
  if(map!=null){
   Set<Entry<String, String>> set=map.entrySet();
   for(Entry<String, String> entry:set){
    params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
   }
  }

  try {
   //将参数按要求保存请求中
   request.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
   HttpResponse response=new DefaultHttpClient().execute(request);

   //判断登录是否成功
   if(response.getStatusLine().getStatusCode()==200){
    //将返回的数据变string保存msg
    msg=EntityUtils.toString(response.getEntity());
   }else if(response.getStatusLine().getStatusCode()==404){

    msg="404-服务器不存在";
   }else if(response.getStatusLine().getStatusCode()==500){
    msg="505-抱歉,登录码编译编译错误";
   }else{
    msg="登录失败";
   }
  } catch (Exception e) {
   e.printStackTrace();
   throw new Exception("登录失败");
  }
  return msg;
 }
}

三:向服务器添加用户类(AddUserActivity)

package com.example.userdatatoweb;

import java.util.HashMap;
import java.util.Map;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.support.v4.app.NavUtils;

public class AddUserActivity extends Activity {
 EditText txtName;
 EditText txtAge;
 EditText txtTel;
 EditText txtAddress;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.adduser
);
        //获取界面控件
        txtName=(EditText) findViewById(R.id.etName);
        txtAge=(EditText) findViewById(R.id.etAge);
        txtTel=(EditText) findViewById(R.id.etTel);
        txtAddress=(EditText) findViewById(R.id.etAddress);
    }
    /**
     * 保存用户
     * */
    public void saveUser(View view){
     //获取界面数据
     String name=txtName.getText().toString();
     String age=txtAge.getText().toString();
     String tel=txtTel.getText().toString();
     String address=txtAddress.getText().toString();
     //map集合封装界面数据
     Map<String, String> map=new HashMap<String, String>();
     map.put("name", name);
     map.put("age", age);
     map.put("tel", tel);
     map.put("address", address);
     try {
   String result=HttpUtil.sendRequest(HttpUtil.addUser, map);
   //跳转用户列表页
   Intent intent=new Intent();
   intent.setClass(this, UserListActivity.class);
   startActivity(intent);
   this.finish();
  } catch (Exception e) {
   Log.i("Web", name+"页面跳转失败");
   e.printStackTrace();
  }
    }

注:添加界面:

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="
http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="1" >
 <TextView
       android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="@string/useradd"
     android:gravity="center"
     android:textSize="18sp" />
 <TextView
       android:layout_width="fill_parent"
     android:layout_height="@dimen/useraddline"
     android:background="#fff"/>
  <TableRow
      android:id="@+id/tableRow2"
       android:layout_width="wrap_content"
      android:layout_height="wrap_content">
      <TextView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="@string/username"/>
      <EditText
          android:id="@+id/etName"
          android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text=""/>
  </TableRow>
  <TableRow
      android:id="@+id/tableRow3"
       android:layout_width="wrap_content"
      android:layout_height="wrap_content">
      <TextView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="@string/userage"/>
      <EditText
          android:id="@+id/etAge"
          android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text=""
       android:numeric="integer"/>
  </TableRow>
  <TableRow
      android:id="@+id/tableRow4"
       android:layout_width="wrap_content"
      android:layout_height="wrap_content">
      <TextView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="@string/usertel"/>
      <EditText
          android:id="@+id/etTel"
          android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text=""
       android:numeric="decimal"/>
  </TableRow>
  <TableRow
      android:id="@+id/tableRow5"
       android:layout_width="wrap_content"
      android:layout_height="wrap_content">
      <TextView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="@string/useraddress"/>
      <EditText
          android:id="@+id/etAddress"
          android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text=""/>
  </TableRow>
  <Button
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="@string/save"
     android:onClick="saveUser" />
</TableLayout>

 

简单web服务器:

原创粉丝点击