Android开发 Json服务端调用

来源:互联网 发布:seo职业发展方向 编辑:程序博客网 时间:2024/06/10 08:32

最近做Android的开发用到了webservice,整理如下,此方法需要在新线程里面调用

android端:

public void loginSupermarket(String url,String userPhoneString,String userPasswordString) {

try {
HttpClient client = new DefaultHttpClient();
HttpPost postjson = new HttpPost(url);//url为服务端的url
ArrayList<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair("selectMethod", "login"));//向服务端发送的参数
nvps.add(new BasicNameValuePair("userPhoneString",userPhoneString ));
nvps.add(new BasicNameValuePair("userPasswordString", userPasswordString));
UrlEncodedFormEntity entityIn = new UrlEncodedFormEntity(nvps,"gbk");//发送的编码格式
postjson.setEntity(entityIn);
HttpResponse response = client.execute(postjson);
HttpEntity entityOut = response.getEntity();//获得返回来的json实体,下面是解析
System.out.println(2);
if (entityOut != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(entityOut.getContent(), "gbk"));


StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
JSONTokener jsonTokener=new JSONTokener(sb.toString());
JSONObject jsonObject=(JSONObject)jsonTokener.nextValue();
if(jsonObject.getBoolean("loginResult"))//下面是跟据服务端返回来的值向子线程发送数据
{
    Message msg = new Message();
           Bundle b = new Bundle();// 存放数据
            b.putBoolean("loginResult", true);
           msg.setData(b);
           Login.this.loginHandler.sendMessage(msg); // 向Handler发送消息,更新UI
}
else {
Message msg = new Message();
           Bundle b = new Bundle();// 存放数据
           //b.putString("result", "我的");
           b.putBoolean("loginResult", false);
           msg.setData(b);
           Login.this.loginHandler.sendMessage(msg); // 向Handler发送消息,更新UI
}
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

服务端//这段在web端的servlet里面

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/json;charset=UTF8");
request.setCharacterEncoding("utf8");
PrintWriter out = response.getWriter();

               String selectMethod=request.getParameter("selectMethod");
           if(selectMethod.equalsIgnoreCase("login"))
        {
            String userPhoneString=request.getParameter("userPhoneString");
       String userPasswordString=request.getParameter("userPasswordString");
       try {
        System.out.println(userPhoneString);
           System.out.println(userPasswordString);
        custom custom1=operateDataForApi.login(userPhoneString, userPasswordString);
      if(custom1!=null)
      {
      System.out.println("true");
      jobj.put("loginResult",true);
      }else
      {
      System.out.println("false");
      jobj.put("loginResult", false);
      }
           out.print(jobj.toString());
      }
       catch (JSONException e) {
// TODO: handle exception
      e.printStackTrace();
     
        }

0 0
原创粉丝点击