1. 程式人生 > >安卓客戶端與開發端connect

安卓客戶端與開發端connect

開發端
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import com.online.dao.Users;
import com.online.dao.UsersOperation;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import javax.servlet.annotation.WebServlet;


@WebServlet(name = "ServletTest")
public class ServletTest extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("servlet action");
        String loginName = request.getParameter("username");
        String loginPassword = request.getParameter("passwd");
        System.out.println(loginName);
        System.out.println(loginPassword);
        Users users=new UsersOperation();
        boolean flag=users.LoginuserCounter(loginName,loginPassword);
        JSONObject jsondata=new JSONObject();
        try {
            jsondata.put("flag",flag);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().println(request.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

web.xml

<servlet>
    <servlet-name>ServletTest</servlet-name>
    <servlet-class>ServletTest</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>ServletTest</servlet-name>
    <url-pattern>/ServletTest</url-pattern>
</servlet-mapping>

安卓端

package com.wm.remusic.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.wm.remusic.R;
import com.wm.remusic.http.HttpUtils;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */

public class LogActivity extends Activity{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.log);
        initView();
    }

    private void initView() {

        final EditText logcount = (EditText) findViewById(R.id.count);
        final EditText logPwd = (EditText) findViewById(R.id.logPwd);
        Button btn = (Button) findViewById(R.id.logBtn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               String count = logcount.getText().toString().trim();
               String pwd = logPwd.getText().toString().trim();



               Map<String,String> data =new HashMap<String,String>();
               data.put("username",count);
               data.put("passwd",pwd);
               String url= HttpUtils.URL+"/Servlet";
               String returndata=HttpUtils.SendPostMethod((List<BasicNameValuePair>) data);
                try {
                    JSONObject jsondata=new JSONObject(returndata);
                    if(jsondata.getBoolean("flag")){
                        Toast.makeText(LogActivity.this, "登入成功!", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(LogActivity.this, "登入失敗!", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        });
    }
}

httputils.java

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class HttpUtils {
    // static final String URL =
    // "http://10.1.1.186:8080/MyServer_andrioid/login.do";
    public static final String URL = "http://localhost:8080/home/zqr/IdeaProjects/musiconlineshop";
    public static final String GETURL = "http://192.168.191.1:8080/MyServer_andrioid/main.do";
    public static final String ENCODING = "UTF-8";
    public static String TAG = "Server responce:";
    public static String result = "it's a test.";

    public static HttpClient httpClient;
    public static HttpPost httpPost;
    public HttpGet httpGet;

    public HttpUtils() {
        httpClient = new DefaultHttpClient();
        httpPost = new HttpPost(URL);
    }

    public static String SendPostMethod(List<BasicNameValuePair> params) {
        try {
            UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(params, ENCODING);
            httpPost.setEntity(encodedFormEntity);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();

            int resCode = httpResponse.getStatusLine().getStatusCode();
            if (resCode == 200) {
                result = (String) EntityUtils.toString(entity, ENCODING);
            }
            httpClient.getConnectionManager().shutdown();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public String SendGetMethod(List<BasicNameValuePair> params) {
        String param = URLEncodedUtils.format(params, ENCODING);
        httpGet = new HttpGet(GETURL + "?" + param);
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int resCode = httpResponse.getStatusLine().getStatusCode();
            if (resCode == 200) {
                result = EntityUtils.toString(httpResponse.getEntity());
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        return result;
    }
}