安卓常用的连接网络的方式:
1.HttpClient:
httpClient是最常用的,需要Apache的jar包
private static DefaultHttpClient httpClient = new DefaultHttpClient();
public static String cookie = null;
public static void get(Map<String, Object> pa, Context context, OnDateRecieceListener listener) {
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("参数名", "参数"));
try {
HttpPost postMethod = new HttpPost(ProjectSetting.baseUrl + "api/AddComment");
postMethod.setHeader("Cookie", cookie); // 如果不需要cookie可以删掉
postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
HttpResponse response = httpClient.execute(postMethod);
String strResult = EntityUtils.toString(response.getEntity()).replace("\t","").replace("\n", "").replace("\r", ""); // 如果是json可以这样处理
JSONObject json = new JSONObject(strResult); if (null != json) { } else { Toast.makeText(context, "连接网络失败,请检查网络", Toast.LENGTH_SHORT).show(); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(context, "数据错误", Toast.LENGTH_SHORT).show(); }}
2. HttpUrlConnection:
httpUrlConnection用得也比较多,简单方便
//cookie处理 public static String sCookie = ""; public static Object urlConnection(String url, String pa, Context context) { Object result = null; try { HttpURLConnection conn = (HttpURLConnection) new URL(ProjectSetting.baseUrl + url).openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); // 不需要cookie可以删掉 if (sCookie != null && !sCookie.isEmpty()) { conn.setRequestProperty("Cookie", sCookie); } // Send data PrintWriter pw = new PrintWriter(conn.getOutputStream()); // pa为请求的参数 pw.print(pa); pw.flush(); pw.close(); // Get the response! int httpResponseCode = conn.getResponseCode(); if (httpResponseCode != HttpURLConnection.HTTP_OK) { throw new Exception("HTTP response code: " + httpResponseCode); } // inputStream为http返回的数据 InputStream inputStream = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String response = ""; String readLine; while (null != (readLine = br.readLine())) { response = response + readLine; } inputStream.close(); // 如果为json可以这样处理 if (!response.isEmpty()) { JSONObject json = JSON.parseObject(response.replace("\t", "").replace("\n", "").replace("\r", "")); result = json; } else { Toast.makeText(context, "连接网络失败,请检查网络", Toast.LENGTH_SHORT).show(); } // 保存cookie String cookie = conn.getHeaderField("set-cookie"); if (cookie != null && cookie.length() > 0) { sCookie = cookie; } conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } return result; }
3.使用android-query框架
private static Context context; private static AjaxCallback<JSONObject> callback = new AjaxCallback<JSONObject>() { @Override public void callback(String url, JSONObject json, AjaxStatus status) { List<Cookie> cookies = status.getCookies(); for (Cookie cookie : cookies) { this.cookie(cookie.getName(), cookie.getValue()); } if (json != null) { try { } catch (JSONException e) { Toast.makeText(context, "数据错误", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } else { Toast.makeText(context, "连接网络失败,请检查网络", Toast.LENGTH_SHORT).show(); } } }; public static void getData(String url, Context con, Map<String, Object> params, AQuery aQuery) { context = con; AbstractAjaxCallback.setReuseHttpClient(true); aQuery.ajax(url, params, JSONObject.class, callback); }