安卓介面請求執行個體

來源:互聯網
上載者:User

標籤:安卓

首先一個工具類

package com.luo.utils;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import java.net.URLDecoder;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;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.ClientProtocolException;import org.apache.http.client.HttpClient;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.client.params.HttpClientParams;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.params.BasicHttpParams;import org.apache.http.params.HttpConnectionParams;import org.apache.http.params.HttpParams;import org.apache.http.params.HttpProtocolParams;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.net.ConnectivityManager;import android.net.http.AndroidHttpClient;import android.util.Log;import android.widget.Toast;/**網路連接 * @author cnmobi-db * */public class MyConnect {private static HttpParams httpParams;private static HttpClient httpClient;/**get方式請求 * @param url * @param params * @return */public static String doGet(String url, Map<String, String> params) { /* 建立HTTPGet對象 */String paramStr = "";Set<Map.Entry<String, String>> set = params.entrySet();  for (Iterator<Map.Entry<String, String>> it = set.iterator(); it.hasNext();) {            Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();            System.out.println(entry.getKey() + "--->" + entry.getValue());            paramStr += paramStr = "&" + entry.getKey() + "=" + entry.getValue();        }if (!paramStr.equals("")) {paramStr = paramStr.replaceFirst("&", "?");url += paramStr;}Log.d("strResult", url);HttpGet httpRequest = new HttpGet(url);String strResult = "doGetError";try {/* 發送請求並等待響應 */HttpResponse httpResponse = httpClient.execute(httpRequest);/* 若狀態代碼為200 ok */if (httpResponse.getStatusLine().getStatusCode() == 200) {/* 讀返回資料 */strResult = EntityUtils.toString(httpResponse.getEntity());} else {//strResult = "Error Response: "//+ httpResponse.getStatusLine().toString();strResult = "404";}} catch (ClientProtocolException e) {//strResult = e.getMessage().toString();strResult = "404";e.printStackTrace();} catch (IOException e) {//strResult = e.getMessage().toString();strResult = "404";e.printStackTrace();} catch (Exception e) {//strResult = e.getMessage().toString();strResult = "404";e.printStackTrace();}Log.d("strResult", strResult);return strResult;}/**post方式請求 * @param session * @param url * @param params * @return */public static String doPost(String session,String url, List<NameValuePair> params) {String www = url +"?";for(int i =0; i<params.size();i++){if(i != params.size()-1)www = www + params.get(i).toString()+"&";elsewww = www + params.get(i).toString();}Log.d("strResult","url---> "+www);/* 建立HTTPPost對象 */HttpPost httpRequest = new HttpPost(url);String strResult = "doPostError";try {/* 添加請求參數到請求對象 */httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));if(session != null){       httpRequest.setHeader("Cookie", session);System.out.println(session);}/* 發送請求並等待響應 */HttpResponse httpResponse = httpClient.execute(httpRequest);/* 若狀態代碼為200 ok */if (httpResponse.getStatusLine().getStatusCode() == 200) {/* 讀返回資料 */strResult = EntityUtils.toString(httpResponse.getEntity(),HTTP.UTF_8); } else {strResult = "404";// "Error Response: " +// httpResponse.getStatusLine().toString();}} catch (UnsupportedEncodingException e) {strResult = "404";// e.getMessage().toString();e.printStackTrace();} catch (ClientProtocolException e) {strResult = "404";// e.getMessage().toString();e.printStackTrace();} catch (IOException e) {strResult = "404";// e.getMessage().toString();e.printStackTrace();} catch (Exception e) {strResult = "404";// e.getMessage().toString();e.printStackTrace();}Log.d("strResult", strResult);try {strResult = URLDecoder.decode(strResult, HTTP.UTF_8);} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}Log.d("strResult", strResult);return strResult;}/**配置httpclient * @return */public static HttpClient getHttpClient() {// 建立 HttpParams 以用來設定 HTTP 參數(這一部分不是必需的)httpParams = new BasicHttpParams();// 設定連線逾時和 Socket 逾時,以及 Socket 緩衝大小HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);HttpConnectionParams.setSocketBufferSize(httpParams, 8192);// 設定重新導向,預設為 trueHttpClientParams.setRedirecting(httpParams, true);// 設定 user agentString userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";HttpProtocolParams.setUserAgent(httpParams, userAgent);// 建立一個 HttpClient 執行個體httpClient = new DefaultHttpClient(httpParams);return httpClient;}/**擷取網路連通狀態 * @param context * @return */public static boolean NetWorkStatus(Context context) {boolean netSataus = false;ConnectivityManager cwjManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);cwjManager.getActiveNetworkInfo();if (cwjManager.getActiveNetworkInfo() != null) {netSataus = cwjManager.getActiveNetworkInfo().isAvailable();}        if(!netSataus)        Toast.makeText(context, "網路錯誤!", Toast.LENGTH_SHORT).show();return netSataus;}/**擷取網狀圖片 * @param url * @return */public static Bitmap loadImageFromInternet(String url) {Bitmap bitmap = null;HttpClient client = AndroidHttpClient.newInstance("Android");HttpParams params = client.getParams();HttpConnectionParams.setConnectionTimeout(params, 3000);HttpConnectionParams.setSocketBufferSize(params, 3000);HttpResponse response = null;InputStream inputStream = null;HttpGet httpGet = null;try {httpGet = new HttpGet(url);response = client.execute(httpGet);int stateCode = response.getStatusLine().getStatusCode();if (stateCode != HttpStatus.SC_OK) {return bitmap;}HttpEntity entity = response.getEntity();if (entity != null) {try {inputStream = entity.getContent();return bitmap = BitmapFactory.decodeStream(inputStream);} finally {if (inputStream != null) {inputStream.close();}entity.consumeContent();}}} catch (ClientProtocolException e) {httpGet.abort();e.printStackTrace();} catch (IOException e) {httpGet.abort();e.printStackTrace();} finally {((AndroidHttpClient) client).close();}return bitmap;}}


然後建立一個非同步任務內部類

class GethispetsAsyncTask extends AsyncTask<Object, Object, Object> {ProgressDialog dialog = ProgressDialog.show(HeActivity.this, null,"正在查詢寵物資訊,請稍後......");private String url;private String token;private String uid;public GethispetsAsyncTask(String url, String token, String uid) {this.url = url;this.token = token;this.uid = uid;}@Overrideprotected Object doInBackground(Object... params) {String code = "1";MyConnect.getHttpClient();Map<String, String> parms = new LinkedHashMap<String, String>();parms.put("token", token);parms.put("uid", uid);String jsonContent = MyConnect.doGet(url, parms);try {JSONObject jsonObject = new JSONObject(jsonContent);if (jsonObject != null) {code = jsonObject.getString("code");if (jsonObject.has("petArray")) {String j1 = jsonObject.getString("petArray");JSONArray j2 = new JSONArray(j1);for (int i = 0; i < j2.length(); i++) {JSONObject jsonObject2 = j2.getJSONObject(i);String j3 = jsonObject2.getInt("weight") + " KG";String j4 = jsonObject2.getString("nickname");String j5 = jsonObject2.getString("birthday");String j6 = jsonObject2.getString("breed");HashMap<String, String> map = new HashMap<String, String>();map.put("weight", j3);map.put("name", j4);map.put("bir", j5);map.put("kind", j6);hispetList.add(map);}}if (jsonObject.has("terminalArray")) {String ter = jsonObject.getString("terminalArray");JSONArray termes = new JSONArray(ter);for (int i = 0; i < termes.length(); i++) {JSONObject jsonObject3 = termes.getJSONObject(i);String terid = jsonObject3.getString("terminalId");String dist = jsonObject3.getString("dist");HashMap<String, String> map1 = new HashMap<String, String>();map1.put("terminalId", terid);map1.put("dist", dist);histerList.add(map1);}}}} catch (JSONException e) {e.printStackTrace();}return code;}@Overrideprotected void onPostExecute(Object result) {super.onPostExecute(result);System.out.println("-----result------>" + result);dialog.dismiss();if (result.equals("0")) {hispetapter = new SimpleAdapter(HeActivity.this, hispetList,R.layout.list_itemhispet, new String[] { "weight","bir", "kind", "name" }, new int[] {R.id.weight, R.id.bir, R.id.kind, R.id.name });listView.setAdapter(hispetapter);histerapter = new SimpleAdapter(HeActivity.this, histerList,R.layout.list_itemhister, new String[] { "terminalId","dist" }, new int[] { R.id.ter, R.id.dist });listView2.setAdapter(histerapter);} else if (result.equals("40008")) {Toast.makeText(HeActivity.this, "身份資訊到期,請重新登入",Toast.LENGTH_SHORT).show();} else {}}}


最後啟動非同步任務

new GethispetsAsyncTask(ConstantUtils.host1 + ConstantUtils.url_26,ConstantUtils.token, uid + "").execute(null, null, null);


安卓介面請求執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.