上傳數據到服務器以及從服務器下載數據
1、json格式上傳數據
/** * * 功能說明:用戶登陸操作創建時間:2012-11-7 下午4:03:41 * * @param name * 用戶名 * @param password * 密碼 void * @throws JSONException * */ public static LoginResponse login(String name, String password) { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("account", name); // 密碼3des加密 jsonObject.put("pwd", TripleDES.getEncString(password, HttpGetConstast.DES_CODE)); String responseStr = HttpPostUtil .doOaPost(HttpGetConstast.BASE_ADDRESS + HttpGetConstast.CLIENT_LOGIN, jsonObject); System.out.println("登陸---->" + responseStr); return responseStr == null ? null : (LoginResponse) gson.fromJson( responseStr, new TypeToken<LoginResponse>() { }.getType()); } catch (JSONException e) { e.printStackTrace(); return null; } }
/** * * 功能說明:通過httpget訪問目標網址 創建時間:2012-11-8 上午9:48:48 * * @param url * 訪問地址 * @param param * 訪問參數 * @param connectTimeOut * 請求超時時間 * @param readTimeOut * 讀取超時時間 * @return String 服務器返回的json字符串 * */ public static String doPost(String url, JSONObject param, int connectTimeOut, int readTimeOut) { HttpPost request = new HttpPost(url); // 先封裝一個 JSON 對象 // 綁定到請求 Entry try { StringEntity se = new StringEntity(param.toString(), HTTP.UTF_8); request.setEntity(se); request.addHeader("Content-Type", "application/json"); request.addHeader("charset", HTTP.UTF_8); request.getParams().setParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeOut); // 讀取超時 request.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeOut); // 發送請求 HttpResponse httpResponse = new DefaultHttpClient() .execute(request); // 得到應答的字符串,這也是一個 JSON 格式保存的數據 String retSrc = EntityUtils.toString(httpResponse.getEntity()); return retSrc; } catch (Exception e) { e.printStackTrace(); return null; } }
浙公網安備 33010602011771號