AsyncTask实现登录功能,上传图片,get,post

提交成功时,从服务器端返回数据“load success”

用户名、密码正确后成功登录,并且在服务器端的文件保存目录上看到了从客户端上传的图片。

客户端代码:

MainActivity.java

  1 import java.io.ByteArrayOutputStream;
  2 import java.net.URLEncoder;
  3 import java.util.ArrayList;
  4 import java.util.List;
  5 
  6 import org.apache.http.HttpResponse;
  7 import org.apache.http.NameValuePair;
  8 import org.apache.http.client.HttpClient;
  9 import org.apache.http.client.entity.UrlEncodedFormEntity;
 10 import org.apache.http.client.methods.HttpGet;
 11 import org.apache.http.client.methods.HttpPost;
 12 import org.apache.http.impl.client.DefaultHttpClient;
 13 import org.apache.http.message.BasicNameValuePair;
 14 import org.apache.http.util.EntityUtils;
 15 
 16 import android.app.Activity;
 17 import android.app.ProgressDialog;
 18 import android.content.Context;
 19 import android.graphics.Bitmap;
 20 import android.graphics.BitmapFactory;
 21 import android.os.AsyncTask;
 22 import android.os.Bundle;
 23 import android.text.TextUtils;
 24 import android.util.Base64;
 25 import android.view.View;
 26 import android.widget.EditText;
 27 import android.widget.Toast;
 28 
 29 public class Activity2 extends Activity {
 30 
 31     private ProgressDialog dialog;
 32     private EditText name;
 33     private EditText pass;
 34     private Context context;
 35     private static final String PATH="http://172.16.30.146:8080/Lesson/servlet/LoginServlet?";
 36     @Override
 37     protected void onCreate(Bundle savedInstanceState) {
 38         super.onCreate(savedInstanceState);
 39         setContentView(R.layout.main2);
 40         context=this;
 41         name=(EditText) findViewById(R.id.name);
 42         pass=(EditText) findViewById(R.id.pass);
 43         dialog= new ProgressDialog(context);
 44         dialog.setCancelable(false);
 45         dialog.setTitle("提示");
 46         dialog.setMessage("下载中,请稍等.....");
 47         dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
 48         
 49         
 50         
 51     }
 52     
 53     public void myget(View v)
 54     {
 55         String myname=name.getText().toString().trim();
 56         String mypass=pass.getText().toString().trim();
 57         if(TextUtils.isEmpty(myname) || TextUtils.isEmpty(mypass))
 58         {
 59             Toast.makeText(context, "用户名或密码不能为空", 1).show();
 60             return;
 61         }
 62         
 63         new MyGetTask().execute(myname,mypass);
 64     }
 65 
 66     /*采用异步任务
 67      * 参数一代表 执行异步任务时传递的参数的类型
 68      * 参数二 如果不采用进度,则填Void,否则填 Integer
 69      * 参数三 是指网络回传回来的数据类型
 70      */
 71     public class MyGetTask extends AsyncTask<String,Void,String>{
 72 
 73         @Override
 74         protected void onPreExecute() {
 75             dialog.show();
 76             super.onPreExecute();
 77         }
 78         @Override
 79         protected String doInBackground(String... params) {
 80             //1.打开浏览器
 81             HttpClient client=new DefaultHttpClient();
 82             //2.输入网址
 83             String urlPath=null;
 84             try {
 85                 urlPath=PATH+"name="+URLEncoder.encode(params[0], "utf-8")+"&pass="+URLEncoder.encode(params[1], "utf-8");
 86             
 87                 //3.执行并得到回应
 88                 HttpResponse response=client.execute(new HttpGet(urlPath));
 89             
 90                 if(response.getStatusLine().getStatusCode()==200)
 91                 {
 92                     
 93                 String str=    EntityUtils.toString(response.getEntity());
 94                 return str;
 95                 }
 96             } catch (Exception e) {
 97                 // TODO Auto-generated catch block
 98                 e.printStackTrace();
 99             }
100             
101         
102             return null;
103         }
104         
105         @Override
106         protected void onPostExecute(String result) {
107             dialog.dismiss();
108             Toast.makeText(context, "得到的回应是:"+result, 1).show();
109             
110             super.onPostExecute(result);
111         }
112         
113     }
114     
115     
116     public void mypost(View v)
117     {
118         String myname=name.getText().toString().trim();
119         String mypass=pass.getText().toString().trim();
120         if(TextUtils.isEmpty(myname) || TextUtils.isEmpty(mypass))
121         {
122             Toast.makeText(context, "用户名或密码不能为空", 1).show();
123             return;
124         }
125         
126         new MyTaskByPost().execute(myname,mypass);
127         
128 /*        
129         */    
130     }
131    
132     public class MyTaskByPost extends AsyncTask<String, Void, String>{
133 
134         //Volley  AsyncHttpClient
135 
136         @Override
137         protected void onPreExecute() {
138             dialog.show();
139             super.onPreExecute();
140         }
141         @Override
142         protected String doInBackground(String... params) {
143             //1.打开浏览器
144             HttpClient client=new DefaultHttpClient();
145             //2.输入网址
146             String urlPath="http://172.16.30.146:8080/Lesson/servlet/LoginServlet";
147             try {
148                 //3.设置向服务器提交的数据
149                 List<NameValuePair> parameters=new ArrayList();
150                 NameValuePair n = new BasicNameValuePair("name",params[0]);
151                 NameValuePair p = new BasicNameValuePair("pass",params[1]);
152                 parameters.add(n);
153                 parameters.add(p);
154                 Bitmap map=BitmapFactory.decodeResource(getResources(), R.drawable.myphoto);
155                 ByteArrayOutputStream out=new ByteArrayOutputStream();
156                 map.compress(Bitmap.CompressFormat.PNG, 100, out);
157                 
158                 byte[] result=out.toByteArray();
159             String img=    Base64.encodeToString(result, 0, result.length, Base64.DEFAULT);
160             
161                 NameValuePair m = new BasicNameValuePair("img",img);
162                 parameters.add(m);
163                 
164             UrlEncodedFormEntity    entity = new UrlEncodedFormEntity(parameters, "utf-8");
165                 
166             HttpPost httpPost = new HttpPost(urlPath);
167             httpPost.setEntity(entity);
168                 //3.执行并得到回应
169                 HttpResponse response=client.execute(httpPost);
170             
171                 if(response.getStatusLine().getStatusCode()==200)
172                 {
173                     
174                 String str=    EntityUtils.toString(response.getEntity());
175                 return str;
176                 }
177             } catch (Exception e) {
178                 // TODO Auto-generated catch block
179                 e.printStackTrace();
180             }
181             
182         
183             return null;
184         }
185         @Override
186         protected void onPostExecute(String result) {
187             dialog.dismiss();
188             Toast.makeText(context, "得到的回应是:"+result, 1).show();
189             
190             super.onPostExecute(result);
191         }
192     }
193 
194 }

activity_main.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent" >
 5 
 6     <TextView
 7         android:id="@+id/textView1"
 8         android:layout_width="wrap_content"
 9         android:layout_height="wrap_content"
10         android:layout_alignParentLeft="true"
11         android:layout_alignParentTop="true"
12         android:layout_marginLeft="36dp"
13         android:layout_marginTop="58dp"
14         android:text="用户名" />
15 
16     <EditText
17         android:id="@+id/name"
18         android:layout_width="wrap_content"
19         android:layout_height="wrap_content"
20         android:layout_alignBaseline="@+id/textView1"
21         android:layout_alignBottom="@+id/textView1"
22         android:layout_marginLeft="53dp"
23         android:layout_toRightOf="@+id/textView1"
24         android:ems="10" >
25 
26         <requestFocus />
27     </EditText>
28 
29     <TextView
30         android:id="@+id/textView2"
31         android:layout_width="wrap_content"
32         android:layout_height="wrap_content"
33         android:layout_alignLeft="@+id/textView1"
34         android:layout_below="@+id/name"
35         android:layout_marginTop="49dp"
36         android:text="密码" />
37 
38     <EditText
39         android:id="@+id/pass"
40         android:layout_width="wrap_content"
41         android:layout_height="wrap_content"
42         android:layout_alignBottom="@+id/textView2"
43         android:layout_alignLeft="@+id/name"
44         android:ems="10"
45         android:inputType="textPassword" />
46 
47     <Button
48         android:id="@+id/button1"
49         android:layout_width="match_parent"
50         android:layout_height="wrap_content"
51         android:layout_alignParentRight="true"
52         android:layout_below="@+id/textView2"
53         android:layout_marginTop="33dp"
54         android:onClick="myget"
55         android:text="get方式向服务器提交数据" />
56 
57     <Button
58         android:id="@+id/button2"
59         android:layout_width="match_parent"
60         android:layout_height="wrap_content"
61         android:layout_alignParentLeft="true"
62         android:layout_below="@+id/button1"
63         android:layout_marginTop="33dp"
64         android:onClick="mypost"
65         android:text="post方式向服务器提交数据" />
66 
67 </RelativeLayout>

清单里注册权限:<uses-permission android:name="android.permission.INTERNET"/>

服务器端代码:

新建Servlet: LoginServlet.java

 1 package com.my.android;
 2 
 3 import java.io.File;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.io.OutputStream;
 7 import java.io.PrintWriter;
 8 
 9 import javax.servlet.ServletException;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 
14 import sun.misc.BASE64Decoder;
15 
16 /**
17  * Servlet implementation class LoginServlet
18  */
19 public class LoginServlet extends HttpServlet {
20     private static final long serialVersionUID = 1L;
21 
22     protected void doGet(HttpServletRequest request,
23             HttpServletResponse response) throws ServletException, IOException {
24 
25         response.setContentType("text/html;charset=utf-8");
26         response.setCharacterEncoding("utf-8");
27 
28         request.setCharacterEncoding("utf-8");
29         String myname = request.getParameter("name");
30         String mypass = request.getParameter("pass");
31         PrintWriter writer = response.getWriter();
32         System.out.println("myname=" + myname + " mypass=" + mypass);
33         
34          
35          
36 
37         String img = request.getParameter("img");
38         byte[] b = new BASE64Decoder().decodeBuffer(img);
39         File file = new File("F:", "myphoto.png");
40         if (!file.exists())
41             file.createNewFile();
42         OutputStream myout = new FileOutputStream(file);
43         myout.write(b);
44         myout.close();
45         
46         
47         
48         writer.write("load success");
49         writer.flush();
50         writer.close();
51     
52 
53     }
54 
55     protected void doPost(HttpServletRequest request,
56             HttpServletResponse response) throws ServletException, IOException {
57         doGet(request, response);
58     }
59 
60 }
原文地址:https://www.cnblogs.com/UniqueColor/p/5283045.html