由于项目的需要,最近研究了一下需要连接网络项目的MVC架构,参考了一下一个新浪微博的开发架构

http://www.open-open.com/lib/view/open1345524526767.html

大体描述如下

需求:项目中接口很多,联网操作在Activity中处理会非常浩大且那一维护

解决方案:将数据提供层和表现层分开,数据层请求接口的数据 , Activity只处理从数据层来的数据,

那我们看一下Activity的实现:

首先定义了一个接口用于规范将来的activty中的方法

1
2
3
4
5
6
7
8
9
10
11
package com.testaijialogic;
 
public interface IAijiaActivity {
 
    void init();// 初始化数据
 
    void initView();// 初始化界面控件
 
    void refresh(Object... param);// 刷新 内容 不知道可变参数的可以再去学习下coreJva
 
}

然后是Activity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package com.testaijialogic;
 
/**
 * MVC
 * M 提供数据
 * V 显示给用户
 * C 把M的数据显示到视图
 */
import java.util.HashMap;
import java.util.List;
 
import com.testaijialogic.domain.PersonEntity;
import com.testaijialogic.widget.PersonAdapter;
 
import android.app.Activity;
import android.app.ProgressDialog;
 
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
 
public class TestAijiaLogicActivity extends Activity implements IAijiaActivity {
    private Context context;
    private ListView listView;
    private ProgressDialog progressDialog;
    private Button button;
    private ListView listView2;
 
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        context = TestAijiaLogicActivity.this;
        Intent intent = new Intent("com.testaijialogic.MainService");// 在首个Activity开启服务
        startService(intent);
        initView();
        init();
        Log.i("Create""=====");
 
    }
 
    protected void onPause() {
 
        super.onPause();
        Log.i("onPause""=====");
    }
 
    protected void onResume() {
 
        super.onResume();
        Log.i("onResume""=====");
    }
 
    protected void onDestroy() {
 
        super.onDestroy();
        android.os.Process.killProcess(android.os.Process.myPid());
 
    }
 
    @Override
    public void init() {// 初始化list的数据
        @SuppressWarnings("rawtypes")
        HashMap param = new HashMap();
        param.put("product""testTask");
        // 加载搜索页面微博信息的任务
        MainService.addActivity(TestAijiaLogicActivity.this);
        Task task = new Task(Task.GETPRODUCT, param, context);
        MainService.newTask(task);// 添加新任务
        progressDialog.show();
 
    }
 
    @Override
    public void refresh(Object... param) {
        @SuppressWarnings("unchecked")
        HashMap map = (HashMap) param[0];// 获取map的数据
 
        List<PersonEntity> personlist = (List<PersonEntity>) map.get("product");
        PersonAdapter personAdapter = new PersonAdapter(context, personlist);
        listView.setAdapter(personAdapter);
 
        List<PersonEntity> subpersonlist = (List<PersonEntity>) map// 加载第二个listview
                .get("subproduct");
        PersonAdapter subpersonAdapter = new PersonAdapter(context,
                subpersonlist);
        listView2.setAdapter(subpersonAdapter);
        progressDialog.dismiss();
        Log.i("测试""setadapter");
 
    }
 
    public void initView() {
        listView = (ListView) findViewById(R.id.listView1);
        listView2 = (ListView) findViewById(R.id.listView2);
        button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                init();
            }
        });
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在获取数据");
 
    }
}

可以看到,表现层只是把数据展示到xml中,没有牵扯到请求接口

下面是数据请求层

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.testaijialogic;
/**
 * 任务实体,由于储存认为信息
 */
import java.util.HashMap;
 
import android.content.Context;
 
public class Task {
 
    public static final int GETPRODUCT = 1;
    public static final int GETPRODUCT2 = 5;
    public static final int MSGACTIVITY = 4;
    public static final int NEWWEIBO = 7;
    public static final int HOMEREFRESH = 3;
    public static final int VIEWWEIBO = 8;
    private int taskId;
    private HashMap taskParams;
    private Context ctx;
 
    public Task(int taskId, HashMap taskParams, Context ctx) {
        super();
        this.taskId = taskId;
        this.taskParams = taskParams;
        this.ctx = ctx; 
    }
 
    public int getTaskId() {
        return taskId;
    }
 
    public void setTaskId(int taskId) {
        this.taskId = taskId;
    }
 
    public HashMap getTaskParams() {
        return taskParams;
    }
 
    public void setTaskParams(HashMap taskParams) {
        this.taskParams = taskParams;
    }
 
    public Context getCtx() {
        return ctx;
    }
 
    public void setCtx(Context ctx) {
        this.ctx = ctx;
    }
}

Person实体,储存人员信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.testaijialogic.domain;
 
public class PersonEntity {
    // {"amount":100,"id":1,"name":"itcastliming"}
    private int id;
    private String name;
    private String amount;
 
    public PersonEntity(int id, String name, String amount) {
        setId(id);
        setAmount(amount);
        setName(name);
    }
 
    /**
     * @return the id
     */
    public int getId() {
        return id;
    }
 
    /**
     * @param id
     *            the id to set
     */
    public void setId(int id) {
        this.id = id;
    }
 
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
 
    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
 
    /**
     * @return the amount
     */
    public String getAmount() {
        return amount;
    }
 
    /**
     * @param amount
     *            the amount to set
     */
    public void setAmount(String amount) {
        this.amount = amount;
    }
 
}

核心网络服务,请求项目的所有接口数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
package com.testaijialogic;
 
/*
 * 获取服务器信息服务
 *  */
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import com.testaijialogic.domain.PersonEntity;
import com.testaijialogic.util.WebSender;
 
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
 
public class MainService extends Service implements Runnable {
 
    private static ArrayList<IAijiaActivity> allActivity = new ArrayList<IAijiaActivity>();
    private static ArrayList<Task> allTasks = new ArrayList<Task>();
    List<String> p = new ArrayList<String>();// post的参数 注意设置成全局变量后只能一次放松一个Post了
    List<String> v = new ArrayList<String>();// post的数值
    public static boolean isRun = false;
 
    public static void newTask(Task t) {
        allTasks.add(t);
    }
 
    public static void addActivity(IAijiaActivity iw) {
        allActivity.add(iw);
    }
 
    public static void removeActivity(IAijiaActivity iw) {
        allActivity.remove(iw);
    }
 
    public static IAijiaActivity getActivityByName(String name) {
        for (IAijiaActivity iw : allActivity) {
            if (iw.getClass().getName().indexOf(name) >= 0) {
                return iw;
            }
        }
        return null;
    }
 
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
 
        isRun = true;
        new Thread(this).start();
        Log.e("=============================", "MainService    onCreate()");
    }
 
    @Override
    public void onDestroy() {
        isRun = false;
        stopSelf();
        super.onDestroy();
 
    }
 
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (isRun) {
            try {
                if (allTasks.size() > 0) {
                    // 执行任务,可以遍历执行多个任务
                    // doTask(allTasks.get(0));
                    for (Task task : allTasks) {
                        doTask(task);
                    }
 
                } else {
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                    }
 
                }
            } catch (Exception e) {
                if (allTasks.size() > 0)
                    allTasks.remove(allTasks.get(0));
                Log.d("error", "------------------" + e);
            }
        }
    }
 
    private Handler handler = new Handler() {
 
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
 
            switch (msg.what) {
            case Task.GETPRODUCT:
                MainService.getActivityByName("TestAijiaLogicActivity")
                        .refresh(msg.obj);// 调用TestAijiaLogicActivity的方法刷新控件
 
                break;
            case Task.GETPRODUCT2:// 个人资料
 
                break;
            case Task.MSGACTIVITY:
 
                break;
            case Task.NEWWEIBO:
 
                break;
            case Task.VIEWWEIBO:
 
                break;
            default:
                break;
            }
        }
 
    };
 
    @SuppressWarnings("unchecked")
    private void doTask(Task task) throws JSONException {
        // TODO Auto-generated method stub
        Message msg = handler.obtainMessage();
        msg.what = task.getTaskId();
 
        switch (task.getTaskId()) {
        case Task.GETPRODUCT:// 获取产品信息
            Log.i("有任务执行", "MainS" + task.getTaskId());
            String urlStr = "http://10.1.49.230/test/testjson.php";
            p.add("product");// 增加post的参数名
            v.add((String) task.getTaskParams().get("product"));// 增加post的参数的值
            String result = WebSender.httpClientSendPost(urlStr, p, v);// 发送httppost请求
 
            List<PersonEntity> personEntities = new ArrayList<PersonEntity>();
            JSONArray jsonArray = new JSONArray(result);
            for (int i = 0; i < jsonArray.length(); i++) {
 
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                PersonEntity personEntity = new PersonEntity(
                        jsonObject.getInt("id"), jsonObject.getString("name"),
                        jsonObject.getString("amount"));
                personEntities.add(personEntity);
 
            }
            /**
             * 第二次请求联网,返回list , 也可以使用多任务处理,但是当前项目中界面的listview特别多所以使用这样
             */
            String suburlStr = "http://10.1.49.230/test/testsubjson.php";
            p.add("product");// 增加post的参数名
            v.add((String) task.getTaskParams().get("product"));// 增加post的参数的值
            String subresult = WebSender.httpClientSendPost(suburlStr, p, v);// 发送httppost请求
 
            List<PersonEntity> subpersonEntities = new ArrayList<PersonEntity>();
            JSONArray subjsonArray = new JSONArray(subresult);
            for (int i = 0; i < jsonArray.length(); i++) {
 
                JSONObject jsonObject = subjsonArray.getJSONObject(i);
                PersonEntity personEntity = new PersonEntity(
                        jsonObject.getInt("id"), jsonObject.getString("name"),
                        jsonObject.getString("amount"));
                subpersonEntities.add(personEntity);
 
            }
 
            @SuppressWarnings("rawtypes")
            HashMap map = new HashMap();
            map.put("product", personEntities);
            map.put("subproduct", subpersonEntities);
            msg.obj = map;
            // msg.obj = personEntities;//如果只需要一个list那用这个就可以
            break;
 
        default:
            break;
        }
        allTasks.remove(task);
        // 通知主线程更新UI
        handler.sendMessage(msg);
    }
 
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
 
    /**
     * 退出应用程序
     *
     * @param context
     */
    public static void exitAPP(Context context) {
        Intent it = new Intent("weibo4android.logic.util.MainService");
        context.stopService(it);// 停止服务
        // 杀死进程 我感觉这种方式最直接了当
        android.os.Process.killProcess(android.os.Process.myPid());
 
    }
 
    public static void finshall() {
 
        for (IAijiaActivity activity : allActivity) {// 遍历所有activity 一个一个删除
            ((Activity) activity).finish();
        }
    }
 
    /**
     * 网络连接异常
     *
     * @param context
     */
    public static void AlertNetError(final Context context) {
        AlertDialog.Builder alerError = new AlertDialog.Builder(context);
        alerError.setTitle("网络错误");
        alerError.setMessage("请检查网络");
        alerError.setNegativeButton("退出"new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                exitAPP(context);
            }
        });
        alerError.setPositiveButton("确定"new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                context.startActivity(new Intent(
                        android.provider.Settings.ACTION_WIRELESS_SETTINGS));
            }
        });
        alerError.create().show();
    }
 
}

网络工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package com.testaijialogic.util;
 
/**
 *网络通信类(已优化)
 * */
 
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
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.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
 
import android.util.Log;
 
public class WebSender {
 
    /*
     * 比较原始的 POST Cookies
     */
    public static String[] sendPost(String urlStr, String[] param,
            String[] value, String cookies) {
        String[] result = { "", "" };
        String paramValue = "";
        StringBuffer buffer = null;
        HttpURLConnection con = null;
 
        try {
            URL url = new URL(urlStr);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");
            // con.setRequestProperty("Content-Type", "text/html");
 
            // set cookies
            if (QHFlag.isNotEmpty(cookies)) {
                con.setRequestProperty("cookie", cookies);
            }
 
            paramValue = WebSender.getParamStr(param, value);
 
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setConnectTimeout(50000);// 设置连接主机超时(单位:毫秒)
            con.setReadTimeout(50000);// 设置从主机读取数据超时(单位:毫秒)
 
            con.connect();// connect open
 
            PrintWriter out = new PrintWriter(con.getOutputStream());// 发送数据
            out.print(paramValue);
            out.flush();
            out.close();
 
            // get cookies
            String cks = con.getHeaderField("set-cookie");
            if (cks != "" && cks != null)
                result[1] = cks;
 
            // get status
            int res = 0;
            res = con.getResponseCode();
 
            // get info response
            if (res == 200 || res == 302) {
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        con.getInputStream(), "UTF-8"));
                buffer = new StringBuffer();
                String line = "";
                while ((line = in.readLine()) != null) {
                    buffer.append(line);
                }
            } else {
                QHFlag.e("Web Response:" + res);
            }
 
            con.disconnect();// Connect Close!
        } catch (Exception e) {
            // e.printStackTrace();
        }
 
        if (buffer.length() != 0 && buffer != null) {
            result[0] = buffer.toString();
        }
        return result;
    }
 
    /*
     * 使用HttpClient对象发送GET请求
     */
    public static String httpClientSendGet(String webUrl) {
        String content = null;
        // DefaultHttpClient
        DefaultHttpClient httpclient = new DefaultHttpClient();
        // HttpGet
        HttpGet httpget = new HttpGet(webUrl);
        // ResponseHandler
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            content = httpclient.execute(httpget, responseHandler);
        } catch (Exception e) {
            e.printStackTrace();
        }
        httpclient.getConnectionManager().shutdown();
        return content;
    }
 
    /*
     * 使用HttpClient对象发送有cookie的GET请求
     */
    public static String httpClientSendGet(String urlStr, String Cookies) {
        String httpUrl = urlStr;
        HttpGet httpGet = new HttpGet(httpUrl);
        try {
            HttpClient httpClient = new DefaultHttpClient();
            httpGet.setHeader("cookie", Cookies);
            // 请求HttpClient,取得HttpResponse
            HttpResponse httpResponse = httpClient.execute(httpGet);
 
            // 请求成功
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 取得返回的字符串
                String strResult = EntityUtils.toString(httpResponse
                        .getEntity());
                return strResult;
            }
        } catch (Exception e) {
        }
        return "0";
    }
 
    /*
     * 使用HttpClient对象发送POST请求
     */
    public static String httpClientSendPost(String urlStr,
            List<String> paraName, List<String> val) {
        String httpUrl = urlStr;
        // HttpPost对象
        HttpPost httpPost = new HttpPost(httpUrl);
 
        // 使用NameValuePair来保存要传递的Post参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
 
        // 添加要传递的参数
        System.out.println("====================================");
        for (int i = 0; i < paraName.size(); i++) {
            params.add(new BasicNameValuePair(paraName.get(i), val.get(i)));
            System.out.println(paraName.get(i) + "->" + val.get(i));
        }
        System.out.println("====================================");
 
        try {
            // 设置字符集
            HttpEntity httpEntity = new UrlEncodedFormEntity(params, "utf-8");
            httpPost.setEntity(httpEntity);
 
            // httpClient对象
            HttpClient httpClient = new DefaultHttpClient();
 
            // 请求HttpClient,取得HttpResponse
            HttpResponse httpResponse = httpClient.execute(httpPost);
 
            // 请求成功
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 取得返回的字符串
                String strResult = EntityUtils.toString(httpResponse
                        .getEntity());
                System.out.println(strResult);
                return strResult;
            }
        } catch (Exception e) {
        }
        return "";
    }
 
    /*
     * 使用HttpClient对象发送POST请求
     */
    public static String httpClientSendPost(String urlStr,
            List<String> paraName, List<String> val, String Cookies) {
        String httpUrl = urlStr;
        // HttpPost对象
        HttpPost httpPost = new HttpPost(httpUrl);
 
        // 使用NameValuePair来保存要传递的Post参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
 
        // 添加要传递的参数
        System.out.println("====================================");
        for (int i = 0; i < paraName.size(); i++) {
            params.add(new BasicNameValuePair(paraName.get(i), val.get(i)));
            System.out.println(paraName.get(i) + "->" + val.get(i));
        }
        System.out.println("====================================");
 
        try {
            // 设置字符集
            HttpEntity httpEntity = new UrlEncodedFormEntity(params, "utf-8");
            httpPost.setEntity(httpEntity);
            httpPost.setHeader("cookie", Cookies);
            // httpClient对象
            HttpClient httpClient = new DefaultHttpClient();
 
            // 请求HttpClient,取得HttpResponse
            HttpResponse httpResponse = httpClient.execute(httpPost);
 
            // 请求成功
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 取得返回的字符串
                String strResult = EntityUtils.toString(httpResponse
                        .getEntity());
                System.out.println(strResult);
                return strResult;
            }
        } catch (Exception e) {
        }
        return "";
    }
 
    public static String uploadBitmap1(String urlString, byte[] imageBytes,
            String cookie) {
        // String boundary = "*****";
        try {
            URL url = new URL(urlString);
            final HttpURLConnection con = (HttpURLConnection) url
                    .openConnection();
            // 允许input、Output,不使用Cache
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
 
            // 设置传送的method=POST
            con.setRequestMethod("POST");
            // setRequestProperty
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Content-Type", "text/html");
            if (cookie != null && cookie != "") {
                Log.i("myEvent", "send cookies value is:" + cookie);
                con.setRequestProperty("cookie", cookie);
            }
            // 从主机读取数据的超时时间(单位:毫秒)
            con.setReadTimeout(50000);
            // 设置连接主机的超时时间(单位:毫秒)
            con.setConnectTimeout(50000);
            // System.out.println(con.getResponseCode());
            // 设置DataOutputStream
            DataOutputStream dsDataOutputStream = new DataOutputStream(
                    con.getOutputStream());
            // dsDataOutputStream.writeBytes(twoHyphen + boundary + endString);
            // dsDataOutputStream.writeBytes("Content-Disposition:form-data;"
            // + "name=\"file1\";filename=\"" + "11.jpg\"" + endString);
            // dsDataOutputStream.writeBytes(endString);
 
            dsDataOutputStream.write(imageBytes, 0, imageBytes.length);
            // dsDataOutputStream.writeBytes(endString);
            // dsDataOutputStream.writeBytes(twoHyphen + boundary + twoHyphen
            // + endString);
            dsDataOutputStream.close();
            int cah = con.getResponseCode();
            if (cah == 200) {
                InputStream isInputStream = con.getInputStream();
                int ch;
                StringBuffer buffer = new StringBuffer();
                while ((ch = isInputStream.read()) != -1) {
                    buffer.append((char) ch);
                }
                return buffer.toString();
            } else {
                return "false";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
 
    }
 
    /**
     * 请求字符串
     * */
    public static String getParamStr(String[] param, String[] value) {
        String res = "";
        if (param.length == value.length) {
            for (int i = 0; i < param.length; i++) {
                res += param[i] + "=" + toUTF8(value[i]) + "&";
            }
        }
        return res.substring(0, res.length() - 1);
    }
 
    public static String toUTF8(String str) {
        String u = str;
        try {
            u = java.net.URLEncoder.encode(u, "UTF-8");
        catch (Exception e) {
 
        }
        return u;
    }
 
}

 

Android架构: MVC 新浪微博的更多相关文章

  1. 一种更清晰的Android架构(转)

    一种更清晰的Android架构   一种更清晰的Android架构 原文链接 : Architecting Android…The clean way? 译者 : Mr.Simple & So ...

  2. Android进阶笔记07:Android之MVC 理解

     1. 为什么需要MVC ? 软件中最核心的,最基本的东西是什么?  答:是的,是数据.我们写的所有代码,都是围绕数据的.      围绕着数据的产生.修改等变化,出现了业务逻辑.      围绕着数 ...

  3. Android架构初探

    #一 背景点评美团合并之后,业务需要整合,我们部门的几条业务需要往美团平台迁移,为了降低迁移成本,开发和维护成本,以及将来可能要做的单元测试,需要对架构进行相应的调整.之前的代码都堆在Activity ...

  4. Android中MVC模型(复合模式)

    mvc是model,view,controller的缩写,mvc包括三个部分: 1.模型(model)对象:是应用程序的主体部分,全部的业务逻辑都应该写在该层. 2.视图(view)对象:是应用程序中 ...

  5. Android中MVC、MVP、MVVM具体解释

    前言 今天有时间就刚好有想写关于这几个名词.对于我来说.事实上这么多名词.思想归根究竟就是要依据项目实际.人员配置来做合理优化,既不能纸上谈兵.又不能畏惧不前.那么合理分阶段架构和完好代码才是关键,本 ...

  6. Android与MVC设计模式

    写在前面,之前做过一段时间移动开发,后来因为工作原因搁浅了,最新重新拿起Android权威编程指南学习,顺道做个学习笔记. 首先呢,我想说无论是计算机科班出身还是培训班出身,都听说过高内聚低耦合以及M ...

  7. Android和MVC

    Activity和Android的mvc模式 http://blog.csdn.net/dengshengjin2234/article/details/8502097   //android涉及到的 ...

  8. 一个Android 架构师的成长之路

    前言 总所周知,当下流行的编程语言有Java.PHP.C.C++.Python.Go等.其中,稳坐榜首的仍然是Java编程语言,且在以面向对象思想占主导的应用开发中,Java往往成为其代名词.Java ...

  9. 架构 MVC MVP MVVM 简介 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

随机推荐

  1. centos6 内核优化

     以下为部分优化参数,具体优化方法还要看情况而定 [root@localhost ~]# vi /etc/sysctl.conf    #末尾添加如下参数 net.ipv4.tcp_syncookie ...

  2. 【集美大学1411_助教博客】团队作业7——Alpha冲刺之事后诸葛亮

    写在前面的话 alpha阶段都顺利完成了,大家这次作业完成得都很认真.我觉得通过这些问题,大家既可以回顾自己的alpha阶段,又可以给beta阶段做一些指引.但看了所有组的博客,没有一个组在这些问题之 ...

  3. JAVA基础第八组(5道题)

    36. 37. 38.[程序38] 题目:写一个函数,求一个字符串的长度,在main函数中输入字符串,并输出其长度. package com.niit.homework1; import java.u ...

  4. 201521123066 《Java程序设计》第四周学习总结

    1. 本周学习总结 1.1 尝试使用思维导图总结有关继承的知识点. 1.2 使用常规方法总结其他上课内容. 1.多态性: (1)概念:相同的方法名,不同的实现方法 (2)instanceof运算符:判 ...

  5. 第2周作业-Java基本语法与类库

    1. 本周学习总结 答:① 定义流程控制的各种条件式是同以前学习的一样,要善于运用快捷键.(例如`a/t` + `/` ) ② 熟悉输入输出的使用,注意输入的变量类型使用相应的输入类. ③ 数组对象: ...

  6. SpringMVC第一篇【介绍、入门、工作流程、控制器】

    什么是SpringMVC? SpringMVC是Spring家族的一员,Spring是将现在开发中流行的组件进行组合而成的一个框架!它用在基于MVC的表现层开发,类似于struts2框架 为什么要使用 ...

  7. 笔记本win10安装node的尖酸历程。。。。。。

    在公司的电脑搭建vue环境分分钟搞定,周末闲的无聊给自己的电脑也搭建一个环境,谁知道这么多的问题,记录下这些问题,希望对那些安装node环境有问题的朋友一些帮助. 1.下载安装node 下载地址htt ...

  8. 框架应用:Mybatis (一) - 入门案例

    ORM框架 在实际开发中,工程中本质的任务是从数据库中获取数据,然后对数据进行操作,又或者写入数据.开发时语言是大多是面向对象的工程语言,这个时候就必须进行工程语言和数据库连接语言的转换,也就是所谓的 ...

  9. JS中基本的一些兼容问题 可能解释的不会太清楚

    做兼容注意: 一如果两个都是属性,用逻辑||做兼容 二如果有一个是方法 用三目运算符做兼容 三多个属性或方法封装函数做兼容 一:谷歌浏览器和火狐浏览器鼠标滚动条兼容 1.document.docume ...

  10. Sql Server——查询(一)

    查询数据就是对数据库中的数据进行筛选显示.显示数据的表格只是一个"虚拟表". 查询 (1)对列的筛选: 1.查询表中所有数据: select * from 表名           ...