Android 使用URLConnection来post数据

/** * @param postUrl * 需要post的地址 * @param map * 存储数据的map * @param handler * 处理message的handler */ public static void postDatas(String postUrl, Map<String, String> map, Handler handler) { HttpURLConnection connection = null; URL url; int result_code; // 拼串 StringBuffer sb = new StringBuffer(); if (map != null) { for (Entry<String, String> e : map.entrySet()) { sb.append(e.getKey()); sb.append("="); sb.append(e.getValue()); sb.append("&"); } sb.substring(0, sb.length() - 1); } try { url = new URL(postUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setConnectTimeout(3000); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStreamWriter osw = new OutputStreamWriter( connection.getOutputStream(), "UTF-8"); osw.write(sb.toString()); osw.flush(); osw.close(); StringBuffer buffer = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader( connection.getInputStream(), "UTF-8")); String temp; while ((temp = br.readLine()) != null) { buffer.append(temp); // br.readLine(); buffer.append("\n"); } JSONObject jsonObject = new JSONObject(buffer.toString()); JSONObject dataObject = jsonObject.getJSONObject("data"); result_code = dataObject.getInt("result"); Message message = Message.obtain(); message.obj = result_code; handler.sendMessage(message); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } }
以上方法需要handler作为处理消息结果;
再写一个fragment里的handler:

private static class MyHandler extends Handler { private final WeakReference<FragmentActivity> refer; private final WeakReference<AccountSetting> fragRefer; public MyHandler(FragmentActivity act, AccountSetting frag) { refer = new WeakReference<FragmentActivity>(act); fragRefer = new WeakReference<AccountSetting>(frag); } @Override public void handleMessage(Message msg) { FragmentActivity act = refer.get(); AccountSetting frag = fragRefer.get(); switch (msg.what) { case MSG_PIC: if (act != null && frag != null && frag.isResumed()) { int result_code = (Integer) msg.obj; if (result_code == 0) { ToastUtils.toastWithMessage(act, "上传成功!"); } else { ToastUtils.toastWithMessage(act, "上传失败!"); } } break; default: break; } } }