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

简介: 一:客户端—服务器连接操作类(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

一:客户端—服务器连接操作类(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服务器:

目录
相关文章
|
3天前
|
PHP Android开发
android通过http上传文件,服务器端用php写(原创)
android通过http上传文件,服务器端用php写(原创)
14 4
|
3天前
|
JSON Android开发 数据格式
android与Web服务器交互时的cookie使用-兼谈大众点评数据获得(原创)
android与Web服务器交互时的cookie使用-兼谈大众点评数据获得(原创)
11 2
|
3天前
|
API Apache Android开发
对于Android的http请求的容错管理
对于Android的http请求的容错管理
|
4天前
|
Ubuntu Android开发 数据安全/隐私保护
【Android平板编程】远程Ubuntu服务器Code-Server编程写代码
【Android平板编程】远程Ubuntu服务器Code-Server编程写代码
|
5天前
|
缓存 负载均衡 安全
深入探索Nginx高性能Web服务器配置与优化
【5月更文挑战第7天】本文深入探讨了Nginx的配置与优化,重点介绍了基础配置参数如`worker_processes`、`worker_connections`和`keepalive_timeout`,以及优化策略,包括使用epoll事件驱动模型、开启gzip压缩、启用缓存、负载均衡和安全配置。此外,还提到了性能调优工具,如ab、nginx-stats和nmon,以助于提升Nginx的性能和稳定性。
|
13天前
|
弹性计算 Shell Apache
某时间段访问apache 服务器的请求IP
【4月更文挑战第29天】
16 2
|
13天前
|
弹性计算 Shell Apache
|
13天前
|
前端开发 JavaScript
同源策略下,服务器会收到浏览器的请求吗?
同源策略下,服务器会收到浏览器的请求吗?
|
2天前
|
负载均衡 固态存储 Linux
阿里云轻量应用服务器、云服务器、gpu云服务器最新收费标准参考
轻量应用服务器、云服务器、gpu云服务器是阿里云服务器产品中,比较热门的云服务器产品类型,不同类型的云服务器产品收费模式与收费标准是不一样的,本文为大家展示这几个云服务器产品的最新收费标准情况,以供参考。
阿里云轻量应用服务器、云服务器、gpu云服务器最新收费标准参考
|
2天前
|
弹性计算 负载均衡 容灾
应用阿里云弹性计算:打造高可用性云服务器ECS架构
阿里云弹性计算助力构建高可用云服务器ECS架构,通过实例分布、负载均衡、弹性IP、数据备份及多可用区部署,确保业务连续稳定。自动容错和迁移功能进一步增强容灾能力,提供全方位高可用保障。
9 0