主入口代码:
package com.tp.soft.app; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.tp.soft.http.HttpUtil; import com.tp.soft.io.IOUtil; import com.tp.soft.util.Constant; public class MainActivity extends Activity implements OnClickListener{ private EditText mUser,mPwd; private Button mSumbit; private ProgressDialog mProgressDialog; private String user; private String pwd; private Handler loginHandler = new Handler(){ @Override public void handleMessage(Message msg) { boolean isNetErr = msg.getData().getBoolean("isNetErr"); if(mProgressDialog != null){ mProgressDialog.dismiss(); } if(isNetErr){ Toast.makeText(MainActivity.this, "当前网络不可用", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(MainActivity.this, "错误的用户名或者密码", Toast.LENGTH_SHORT).show(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mUser = (EditText) findViewById(R.id.userEdit); mPwd = (EditText) findViewById(R.id.pwdEdit); mSumbit = (Button) findViewById(R.id.logBtn); mSumbit.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override protected void onDestroy() { if(mProgressDialog != null){ mProgressDialog.dismiss(); } super.onDestroy(); } @Override public void onClick(View v) { mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage("正在登录,请稍等..."); mProgressDialog.show(); user = mUser.getText().toString(); pwd = mPwd.getText().toString(); if(validateInfo(user, pwd)){ Thread loginThread = new Thread(new LoginHandler()); loginThread.start(); } } private boolean validateInfo(String user, String pwd) { if("".equals(user)){ mProgressDialog.dismiss(); Toast.makeText(MainActivity.this, "用户名不能为空", Toast.LENGTH_SHORT).show(); //setMsg("isEmptyUser"); return false; } if("".equals(pwd)){ mProgressDialog.dismiss(); Toast.makeText(MainActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show(); //setMsg("isEmptyPwd"); return false; } return true; } private void setMsg(String msg, boolean isHas){ Message message = new Message(); Bundle bundle = new Bundle(); bundle.putBoolean(msg, isHas); message.setData(bundle); loginHandler.sendMessage(message); } private void setInfo(JSONObject obj) { SharedPreferences sp = this.getSharedPreferences("userInfo", MODE_APPEND); Editor edit = sp.edit(); try { edit.putString("LOGIN_NAME", obj.getString("login_name")); } catch (JSONException e) { e.printStackTrace(); } edit.commit(); } /** * loginState 0(无网络) 1(帐号密码错误) 2(成功) * @param params * @param serverPath * @return */ private int validateLogin(Map<String, String> params, String serverPath){ int loginState = 0; HttpResponse response = HttpUtil.getHttpResonse(serverPath, params, Constant.ENCODING); if(null != response){ if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ IOUtil ioUtil = new IOUtil(); try { String resultJson = ioUtil.getJson(response.getEntity().getContent()); JSONObject jsonObject = new JSONObject(resultJson); boolean isSuccess = jsonObject.getBoolean("success"); if(isSuccess){ //Result r = JSONArray.parseObject(resultJson, Result.class); //if(r.isSuccess()){ //setInfo(r); //} JSONObject userJson = jsonObject.getJSONObject("data").getJSONObject("user"); setInfo(userJson); loginState = 2; }else{ loginState = 1; } } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } }else{ loginState = 0; } } return loginState; } class LoginHandler implements Runnable { @Override public void run() { String serverPath = Constant.LOGINURL; Map<String, String> params = new HashMap<String, String>(); params.put("username", user); params.put("password", pwd); int status = validateLogin(params, serverPath); if(status == 0){ setMsg("isNetErr", true); }else if(status == 1){ setMsg("isNetErr", false); }else if(status == 2){ Intent intent = new Intent(); intent.setClass(MainActivity.this, ShowActivity.class); startActivity(intent); finish(); } } } }
HttpClient封装:
package com.tp.soft.http; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.protocol.HTTP; import android.util.Log; /** * httpClient封装 * @author taop * */ public class HttpUtil { public static HttpResponse getHttpResonse(String serverPath, Map<String, String> params, String encoding){ List<NameValuePair> pairs = new ArrayList<NameValuePair>(); if(null != params && !params.isEmpty()){ for(Map.Entry<String, String> entry : params.entrySet()){ pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } HttpResponse response = null; try{ HttpPost post = new HttpPost(serverPath); post.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8)); response = getHttpClient().execute(post); }catch (ConnectTimeoutException e) { Log.e("提示", "连接超时"); return null; } catch (SocketTimeoutException e) { Log.e("提示", "Socket连接超时"); return null; } catch (Exception e) { Log.e("提示", e.getLocalizedMessage()); return null; } return response; } public static HttpClient getHttpClient() { BasicHttpParams httpParams = new BasicHttpParams(); ConnManagerParams.setTimeout(httpParams, 1000); /* 连接超时 */ HttpConnectionParams.setConnectionTimeout(httpParams, 3000);// 设置请求超时3秒钟 /* 请求超时 */ HttpConnectionParams.setSoTimeout(httpParams, 3000);// 设置等待数据超时时间3秒钟 HttpClient client = new DefaultHttpClient(httpParams); return client; } }
IO封装:
package com.tp.soft.io; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class IOUtil { public String getJson(InputStream is){ String jsonData = ""; InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String resData = ""; try { while((resData=br.readLine())!=null){ jsonData += resData; } } catch (IOException e) { e.printStackTrace(); }finally{ try { br.close(); isr.close(); } catch (IOException e) { e.printStackTrace(); } } return jsonData; } }
Constant类:
package com.tp.soft.util; public class Constant { public final static String ENCODING = "UTF-8"; public final static String SERVER_PATH = "http://xxx.xxx.xxx.xxx:8081/wsTest1/ws/rest/"; public final static String LOGIN_METHOD = "login"; public final static String LOGINURL = SERVER_PATH + "loginService/" + LOGIN_METHOD; }
服务器用的是rest版的webservice
代码:
package com.tp.soft.web.ws.impl; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.apache.log4j.Logger; import org.springframework.dao.DataAccessException; import com.tp.soft.web.common.entity.Result; import com.tp.soft.web.common.exception.BaseServiceException; import com.tp.soft.web.common.util.Constant; import com.tp.soft.web.dao.LoginDao; import com.tp.soft.web.entity.po.AuUser; import com.tp.soft.web.entity.vo.AuUserVo; import com.tp.soft.web.ws.LoginService; @Path("/loginService") public class LoginServiceImpl implements LoginService{ private static final Logger LOG = Logger.getLogger(LoginServiceImpl.class); @Resource(name="loginDao") private LoginDao loginDao; @POST @Path(value="/login") @Produces(MediaType.APPLICATION_JSON) public Result doLogin(@FormParam(value="username") String username, @FormParam(value="password") String password) { Result result = new Result(); AuUserVo auUserVo = new AuUserVo(); auUserVo.setLogin_name(username); AuUser auUser; try{ auUser = loginDao.findUser(auUserVo); }catch (DataAccessException e) { LOG.error("【ibatis】登录异常", e); throw new BaseServiceException(e.getLocalizedMessage()); } if(null == auUser){ result.setErrMsg(Constant.LOGIN_NAME_ERROR); }else if(!password.equals(auUser.getLogin_pwd())){ result.setErrMsg(Constant.LOGIN_PWD_ERROR); }else{ result.setSuccess(true); Map<String, Object> map = new HashMap<String, Object>(); map.put("user", auUser); result.setData(map); } return result; } }
dao里面就是ibatis调用数据库 这边就不贴了