和后台交互

来源:互联网 发布:2017nba球员数据排名 编辑:程序博客网 时间:2024/06/13 13:40
需要交互的页面
  sp = getSharedPreferences("HJSmartRouter", MODE_PRIVATE);  userId = sp.getString("userId", null);  token = sp.getString("token", null);  System.out.println("=========="+userId);
  //获取个人资料  GetPersonalInfoRequest getPersonalInfoRequest = new GetPersonalInfoRequest();  getPersonalInfoRequest.setUserId(userId);  getPersonalInfoRequest.setToken(token);  //事件名称,回调事件,要发送的包  new Thread(new HJHttpUrlConnectionUtil("getPersonalInfo", PersonalInfoHandler, getPersonalInfoRequest)).start();
回调
 public Handler PersonalInfoHandler = new Handler() {  public void handleMessage(Message msg) {   byte[] responseJson = msg.getData().getByteArray("responseJson");   try {    getPersonalInfoResponse = mMapper.readValue(responseJson,      new TypeReference<GetPersonalInfoResponse>() {         });   } catch (Exception e) {    e.printStackTrace();   }   mText_name.setText(getPersonalInfoResponse.getBody().getNickName());   mText_gender.setText(getPersonalInfoResponse.getBody().getSex());   mText_email.setText(getPersonalInfoResponse.getBody().getMailAddress());   List<String> strings = getPersonalInfoResponse.getBody().getPersonalityLabel();   mList = strings;//   String [] str = strings.get(0).split(";");//   for (int i = 0; i < str.length; i++) {//    //    //   }   Toast.makeText(HJMyselfDataActivity.this,     getPersonalInfoResponse.getErrorCode(), Toast.LENGTH_LONG)     .show();  } };
交互的工具类
package com.hanju.util;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintWriter;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.ProtocolException;import java.net.URL;import org.codehaus.jackson.map.ObjectMapper;import android.os.Bundle;import android.os.Handler;import android.os.Message;public class HJHttpUrlConnectionUtil implements Runnable {/* * 请求工具类(POST请求) */private String urlPath;private ObjectMapper mMapper;private String action;private Handler handler;private Object requestObject;public HJHttpUrlConnectionUtil(String action, Handler handler, Object requestObject) {this.action = action;this.handler = handler;this.requestObject = requestObject;}@Overridepublic void run() {HttpURLConnection connection = null;Message msg = null;try {mMapper = new ObjectMapper();String requestJson = mMapper.writeValueAsString(requestObject);urlPath = "http://192.168.0.37:8080/HJSmartRouterServer/";URL postUrl = new URL(urlPath + action);System.out.println("请求路径:" + postUrl);connection = (HttpURLConnection) postUrl.openConnection();connection.setRequestMethod("POST");connection.setReadTimeout(5000);connection.setDoOutput(true);connection.setDoInput(true);connection.setRequestProperty("accept", "*/*");  connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");connection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接connection.setRequestProperty("Charset", "UTF-8");connection.setRequestProperty("Content-Length", String.valueOf(requestJson.length())); System.out.println("准备连接!");connection.connect();System.out.println("完成连接!");OutputStream outPutStream = connection.getOutputStream();PrintWriter printWrite = new PrintWriter(outPutStream);printWrite.write(requestJson);printWrite.flush();System.out.println("返回参数:" + connection.getResponseCode());if(connection.getResponseCode() == 200) {System.out.println("请求成功!");InputStream is = connection.getInputStream();ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = -1;while((len = is.read(buffer)) != -1) {baos.write(buffer, 0, len);}baos.close();is.close();byte[] data = baos.toByteArray();Bundle bundle = new Bundle();bundle.putByteArray("responseJson", data);msg = new Message();msg.setData(bundle);handler.sendMessage(msg);}} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {System.out.println("连接超时");e.printStackTrace();}finally{connection.disconnect();}}}

0 0