AsyncTask异步上传文本到服务器
服务器代码:用于接收客户端信息
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
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.asynctask4.MainActivity" > <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginTop="24dp" android:ems="10" android:inputType="textPersonName" /> <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText1" android:layout_below="@+id/editText1" android:layout_marginTop="14dp" android:ems="10" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText2" android:layout_below="@+id/editText2" android:layout_marginLeft="23dp" android:layout_marginTop="29dp" android:text="上传文本" /> </RelativeLayout>
xmlx效果图:
-----------------------------------------------------------------------------------------------------------------------------
还有一点很重要:就是要给联网的权限
<uses-permission android:name="android.permission.INTERNET"/> 【数据联网】
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>【WIFI联网】
------------------------------------------------------------------------------------------------------------------------------
客户端
服务器接收的结果:---------------------------------------------------------------------------------