android post的数据的时候,一些参数设置如下:
ObjectMapper mapper = new ObjectMapper(); Map<String, Object> paramsList = new HashMap<String, Object>(); HttpPost requestPost = new HttpPost(url); requestPost.setHeader("charset", HTTP.UTF_8); //httppost.addHeader("Content-Type", "application/json"); //requestPost.addRequestHeader("Content-Type","text/html;charset=UTF-8"); /*//封装JSON对象 JSONObject paramsList = new JSONObject();*/ int[] promotions = {1,2}; paramsList.put("shop_id", "14"); paramsList.put("order_id", "77"); paramsList.put("promotion", promotions); paramsList.put("feedbackInfo", "有空调,有免费的WiFi哦"); paramsList.put("feedbackTime", "1404882661000"); content = mapper.writeValueAsString(paramsList); //绑定到请求 Entry StringEntity se = new StringEntity(content, HTTP.UTF_8");//paramsList.toString() requestPost.setEntity(se); //放松请求 HttpResponse httpResponse = new DefaultHttpClient().execute(requestPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { // 可能空指针 String response = EntityUtils.toString( httpResponse.getEntity(), HTTP.UTF_8); Log.d(LOG_TAG, response); return response;} ObjectMapper是开源框架jackson
因为post没法直接添加数组,所以可以使用ObjectMapper.writeValueAsString()方法是把JSONObject转化成字符串的方法。
下面的参数设置较简单,只是一般JSON的设置:
HttpPost request = new HttpPost(url); // 先封装一个 JSON 对象 JSONObject param = new JSONObject(); param.put("name", "rarnu"); param.put("password", "123456"); // 绑定到请求 Entry StringEntity se = new StringEntity(param.toString()); request.setEntity(se); // 发送请求 HttpResponse httpResponse = new DefaultHttpClient().execute(request); // 得到应答的字符串,这也是一个 JSON 格式保存的数据 String retSrc = EntityUtils.toString(httpResponse.getEntity()); // 生成 JSON 对象 JSONObject result = new JSONObject( retSrc); String token = result.get("token");