博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
AsyncTask异步上传文本到服务器
阅读量:5037 次
发布时间:2019-06-12

本文共 5785 字,大约阅读时间需要 19 分钟。

 

服务器代码:用于接收客户端信息

package ches;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet("/chess")public class chess extends HttpServlet {        public chess() {        super();    }        public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {            this.doPost(request, response);        }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {                    String username = request.getParameter("name");            String password =  request.getParameter("sex");                        System.out.println(username);            System.out.println(password);            }}

 

 

接下来是android 项目搭建

创建一个异步请求  asyncText类

package com.example.asynctask4;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLEncoder;import android.os.AsyncTask;import android.util.Log;import android.widget.Toast;public class asyncText extends AsyncTask{private static final String Url = "http://192.168.1.37:8080/ches/chess";private String name,sex;private MainActivity activity;private String errorMessage = "";private String messageInfo = "";public asyncText(MainActivity activity){    this.activity= activity;}    @Override    protected Object doInBackground(Object... params) {        name = (String) params[0];        sex = (String) params[1];                try {            URL url = new URL(Url);                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();        //对连接进行配置        conn.setDoInput(true);        conn.setDoOutput(true);        conn.setUseCaches(false);        conn.setConnectTimeout(3000);        conn.setRequestMethod("POST");                    //获取一个输出流        OutputStream os = conn.getOutputStream();        //上传文本数据        DataOutputStream dos = new DataOutputStream(os);        dos.writeBytes("name="+URLEncoder.encode(name,"UTF-8")+"&sex="+URLEncoder.encode(sex,"UTF-8"));        dos.flush();        dos.close();                if(conn.getResponseCode()==200){            //输入流            InputStream is = conn.getInputStream();                        //reader(注意UTF-8读)            InputStreamReader isr = new InputStreamReader(is,"UTF-8");            //缓冲区,防止读死            BufferedReader br = new BufferedReader(isr);            String ReadOneline = null;                        //多行数据时,减少不断创建String对象            StringBuffer sb = new StringBuffer();            while ( (ReadOneline=br.readLine())!=null ){                sb.append(ReadOneline);            }            br.close();            isr.close();            is.close();            conn.disconnect();            return sb.toString();        }else{            errorMessage = "服务器繁忙,请稍后再试("+conn.getResponseCode()+")";            return "errorserver";        }        } catch (Exception e) {            Log.i("http", "http执行_获取异常");            errorMessage = e.getMessage();            return "errorclient";        }            }    @Override        protected void onPostExecute(Object result) {            // TODO Auto-generated method stub                if ("errorclient".equals(result)){            Toast.makeText(activity, "连接不到服务器"+messageInfo, 500).show();            return;        }if("errorserver".equals(result)){            Toast.makeText(activity, "服务器正在维护中"+messageInfo, 500).show();            return;        }if("ok".equals(result)){            Toast.makeText(activity, "注册成功", 500).show();        }                            super.onPostExecute(result);        }}

 

 

MainActivity.java

 

package com.example.asynctask4;import android.app.Activity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;public class MainActivity extends Activity {    private EditText editText1,editText2;    private Button button;    private String name,sex;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                editText1 = (EditText) findViewById(R.id.editText1);           editText2 = (EditText) findViewById(R.id.editText2);           button = (Button) findViewById(R.id.button1);                      button.setOnClickListener(new OnClickListener() {                        @Override            public void onClick(View v) {              name = editText1.getText().toString().trim();              sex = editText2.getText().toString().trim();                asyncText as = new asyncText(MainActivity.this);//传值到异步多线程                as.execute(name,sex);//执行            }        });    }                 }

 

 

 

activity_main.xml

xmlx效果图:

 -----------------------------------------------------------------------------------------------------------------------------

 

还有一点很重要:就是要给联网的权限

<uses-permission android:name="android.permission.INTERNET"/>    【数据联网】

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>【WIFI联网】

 

------------------------------------------------------------------------------------------------------------------------------

客户端

 

 

 

服务器接收的结果:---------------------------------------------------------------------------------

 

转载于:https://www.cnblogs.com/896240130Master/p/6242019.html

你可能感兴趣的文章
Warsaw University Contest Petrozavodsk, Thursday, January 31, 2008 F题,Gym100096F
查看>>
lcx端口转发 linux版
查看>>
arcgis server 10.1 发布动态图层展示海量及频繁更新的数据步骤
查看>>
strncat_s
查看>>
避免复制引用程序集的XML文件
查看>>
C IO(一般性)
查看>>
机器学习中的贝叶斯方法---先验概率、似然函数、后验概率的理解及如何使用贝叶斯进行模型预测(2)...
查看>>
SQL Server 2005 数据库 可疑状态
查看>>
L1-Day4
查看>>
搭建mocha测试环境并使用selenium进行测试
查看>>
Javascript测试之karma + mocha
查看>>
双城记开头
查看>>
烦人的幻灯片问题
查看>>
最大密度子图
查看>>
基于SSM-EasyUI的权限管理系统
查看>>
观察者模式
查看>>
[CSAPP-II] 链接[符号解析和重定位] 静态链接 动态链接 动态链接接口
查看>>
一起啃PRML - 1 Introduction 绪论
查看>>
git 的基本命令
查看>>
性能优化1
查看>>