2013年7月6日 星期六

Android http post (file) + responsed json handling

以下code包含:建立一個連線, post file or value, 處理回傳的json 首先是http request post的部分: //設定連線timeout HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = 5000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); //設定等待socket回傳timeout int timeoutSocket = 8000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpClient httpclient = new DefaultHttpClient(httpParameters); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); //建立post request HttpPost httppost = new HttpPost("http://xxxxx.php"); //要傳送的檔案 File file = new File(filePath); //android post傳送檔案內建好像只提供自己建立http header然後再手動在content中包入檔案的方式,頗麻煩,這邊使用apache的library來加入檔案. MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file); mpEntity.addPart("File", cbFile); httppost.setEntity(mpEntity); //執行 HttpResponse response = httpclient.execute(httppost); 如果沒有要傳送檔案的話可以這樣: List nameValuePairs = new ArrayList(2); nameValuePairs.add(new BasicNameValuePair("id", "12345")); nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 接著拿到response以後做json處理. BasicResponseHandler handler = new BasicResponseHandler(); String responseString = handler.handleResponse(response); //將回應的string parse成json 物件 JSONObject json = new JSONObject(responseString); //取值範例 if(json.has("Status")) { String status = json.getString("Status"); }

沒有留言:

張貼留言