- <span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">要求:</span>
Android编写一个登录界面,输入用户名和密码,使用JSON格式提交到服务器端。
服务器端收到后返回(JSON格式数据):
“输入的用户”+您好,你已成功登录系统。
“输入的用户”+您好,你已成功登录系统。
其实不管是JSON还是其他类型,都是为了满足Android与服务器端的程序进行数据交换的要求而已
本次笔记的个人觉得
重点如下:
1.服务器端的数据接收
1)包括数据编码的设定
发送与接受最好都用utf-8来设定编码来
在doPost中加入Response声明
- <span style="white-space:pre"> </span>response.setCharacterEncoding("UTF-8");
- <span style="white-space:pre"> </span>response.setContentType("UTF-8");
2)了解异步线程的用途与如何用异步线程AsyncTask 来更新UI
首先,什么时候需要用到异步线程呢,在需要进行对网络发送接收稍大量的数据的时候,或者占用稍大时间,影响了用户体验而又不是必要的等待时间时,就要用到异步。
然后异步线程的大概用法是这样:
- public class JSONOperation extends AsyncTask<JSONObject, Void, String>
里面重写的doInBackgroud(JSONObject... JSONObjs) 就是执行的函数,主要用来执行任务主要内容(在这个例子中主要是进行与服务器端的JSON数据包发送与接受,但不包括对Activity的UI更新操作)。然后可以通过返回一个类型的值比如返回一个String或者JSONObject来给下面重写的onPostExecute方法进行对ActivityUI的更新。
比如说 protected String doInBackground(JSONObject... JSONObjs) 方法 发送到服务器端,并且服务器又发送了一个JSON数据包回来,然后这个方法就可以return这个JSON数据包
然后在下面的onPostExecute(JSONObject obj)就对刚刚doInBackground中的JSONObject类型进行引用,在里面可以添加对UI的操作比如TextView的更新什么的。
如果在doInBackground中执行UI更新操作,就会返回android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
这个错误意思是
只有原始创建这个视图层次(view hierachy)的线程才能修改它的视图(view)
实现:
Servlet中的doPost代码
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setCharacterEncoding("UTF-8");
- response.setContentType("UTF-8");
- StringBuffer sb = new StringBuffer("");
- String result = "";
- try {
- BufferedReader br = new BufferedReader(new InputStreamReader(
- request.getInputStream(), "utf-8"));
- String temp;
- while ((temp = br.readLine()) != null) {
- sb.append(temp);
- }
- br.close();
- result = sb.toString();
- //打印android端上传的JSON数据
- System.out.println(result);
- } catch (Exception e) {
- e.printStackTrace();
- }
- JSONObject jsonObject = JSONObject.fromObject(result);
- String name = jsonObject.getString("username");
- String password=jsonObject.getString("password");
- PrintWriter pw = response.getWriter();
- //封装服务器返回的JSON对象
- JSONObject jsonReply = new JSONObject();
- jsonReply.put("ConnectName",name);
- jsonReply.put("ConnectPass", password);
- //打印返回的JSON数据
- System.out.println(jsonReply);
- //pw.write("连接成功!");
- //BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(jsonReply."utf-8"));
- pw.write(jsonReply.toString());
- pw.flush();
- pw.close();
- }
==Android==
1.别忘了添加网络权限
2.别忘了修改ip地址 Address
界面代码:
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/RelativeLayout1"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- 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=".Main" >
- <TextView
- android:id="@+id/TextView_UserName"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_alignParentTop="true"
- android:layout_marginLeft="20dp"
- android:layout_marginTop="22dp"
- android:text="@string/String_UserName" />
- <EditText
- android:id="@+id/EditText_UserName"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_alignBaseline="@+id/TextView_UserName"
- android:layout_alignBottom="@+id/TextView_UserName"
- android:layout_toRightOf="@+id/TextView_UserName"
- android:ems="10"
- android:inputType="text" >
- <requestFocus />
- </EditText>
- <TextView
- android:id="@+id/TextView_PassWord"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/EditText_UserName"
- android:layout_marginTop="42dp"
- android:layout_toLeftOf="@+id/EditText_UserName"
- android:text="@string/String_PassWord" />
- <EditText
- android:id="@+id/EditText_PassWord"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_alignBaseline="@+id/TextView_PassWord"
- android:layout_alignBottom="@+id/TextView_PassWord"
- android:layout_toRightOf="@+id/TextView_PassWord"
- android:ems="10"
- android:inputType="textPassword" >
- <requestFocus />
- </EditText>
- <Button
- android:id="@+id/Button_Login"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/EditText_PassWord"
- android:layout_centerHorizontal="true"
- android:layout_marginTop="34dp"
- android:text="@string/String_Login" />
- <TextView
- android:id="@+id/TextView_Result"
- android:layout_width="match_parent"
- android:layout_height="180dp"
- android:layout_below="@+id/Button_Login"
- android:layout_centerHorizontal="true"
- android:layout_marginTop="32dp"
- android:text="@string/String_Result" />
- </RelativeLayout>
Activity
- package bnuz.alt.wechat;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.UnsupportedEncodingException;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.util.EntityUtils;
- import org.json.JSONException;
- import org.json.JSONObject;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.app.Activity;
- import android.util.Log;
- import android.view.Menu;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
- import android.widget.Toast;
- public class Main extends Activity {
- private EditText ET_UserName, ET_PassWord;
- private TextView TV_Result;
- private Button BT_Login;
- private String UserName, PassWord;
- private static final String ServerAddress = "http://113.103.144.143:8080/ServerJsonDemo/servlet/JsonServlet",
- TAG = "ATag";
- private String Result_FromServer;
- private JSONObject JsonObj;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- ET_UserName = (EditText) findViewById(R.id.EditText_UserName);
- ET_PassWord = (EditText) findViewById(R.id.EditText_PassWord);
- TV_Result = (TextView) findViewById(R.id.TextView_Result);
- BT_Login = (Button) findViewById(R.id.Button_Login);
- BT_Login.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- UserName = ET_UserName.getText().toString();
- PassWord = ET_PassWord.getText().toString();
- JsonObj = makeUserInfo(UserName, PassWord);
- if (UserName.equals("")) {
- Toast.makeText(getApplicationContext(), "请输入用户名",
- Toast.LENGTH_LONG).show();
- }
- if (PassWord.equals("")) {
- Toast.makeText(getApplicationContext(), "请输入密码",
- Toast.LENGTH_LONG).show();
- }
- if (!PassWord.equals("") && !UserName.equals("")) {
- Toast.makeText(getApplicationContext(), "登陆中...",
- Toast.LENGTH_LONG).show();
- JSONOperation sendJsonTask = new JSONOperation();
- sendJsonTask.execute(JsonObj);
- }
- }
- });
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.main, menu);
- return true;
- }
- public JSONObject makeUserInfo(String userName, String passWord) {
- JSONObject UserInfo = new JSONObject();
- try {
- UserInfo.put("username", userName);
- UserInfo.put("password", passWord);
- } catch (JSONException e) {
- throw new RuntimeException(e);
- }
- return UserInfo;
- }
- public void UpdateResult(String connectName, String connectPass) {
- TV_Result.append("\n用户名:" + connectName + "\n密码" + connectPass);
- }
- public class JSONOperation extends AsyncTask<JSONObject, Void, String> {
- @Override
- protected String doInBackground(JSONObject... JSONObjs) {
- String Result_Show = null;
- HttpClient httpclient = new DefaultHttpClient();
- HttpPost httppost = new HttpPost(ServerAddress);
- try {
- httppost.setEntity(new StringEntity(JsonObj.toString()));
- HttpResponse httpres = httpclient.execute(httppost);
- if (httpres.getStatusLine().getStatusCode() == 200) {
- Log.d(TAG, "成功连接信号");
- String Res = EntityUtils.toString(httpres.getEntity());
- JSONObject JsonResult = new JSONObject(Res);
- // String Result_Name = JsonResult.getString("ConnectName");
- // String Result_PassWord = JsonResult
- // .getString("ConnectPass");
- Result_Show = JsonResult.toString();
- Log.d(TAG,Result_Show);
- }
- } catch (Exception e) {
- Log.d(TAG, e.toString());
- }
- return Result_Show;
- }
- @Override
- protected void onPostExecute(String result) {
- TV_Result.append("\n"+result);
- TV_Result.append("\n你好,你已經成功登陸系統");
- super.onPostExecute(result);
- }
- }
- }
效果图:
Servlet端
Android