网上已经很多post提交数据的文章了, 但以application/json流的方式提交, 却很少提及, 在GOOGLE大神的指点下, 找到
- @SuppressWarnings("deprecation")
- public static JSONObject postData(String jsoncontent,String urlstr) {
- JSONObject jsonobj = null;
- try {
- HttpClient httpclient = new DefaultHttpClient();
- HttpPost httppost = new HttpPost(urlstr);
- //添加http头信息 , 主要是application/json声明
- httppost.addHeader("Content-Type", "application/json");
- //StringEntity就是以字符串输出到流
- HttpEntity he = new StringEntity(jsoncontent,HTTP.UTF_8);
- httppost.setEntity(he);
-
- //如果是以参数传, 就是这个
- // List<NameValuePair> params = new ArrayList<NameValuePair>();
- // params.add(new BasicNameValuePair("paramname", "post data"));
- // httppost.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8));
-
- HttpResponse response;
- response = httpclient.execute(httppost);
- //检验状态码200表示成功
- int code = response.getStatusLine().getStatusCode();
- if (code == 200) {
- String returnjson = EntityUtils.toString(response.getEntity());//返回json格式
- jsonobj = new JSONObject(returnjson);
- }
- } catch (ClientProtocolException e) {
- } catch (IOException e) {
- } catch (Exception e) {
- }
把上面的这个方法放到一个util下, 直接用就好了, jsoncontent是一个JSON字符串, 我是以:
JSONObject postdata = new JSONObject();
postdata.put("name","abc");
String jsoncontent = postdata.toString();
加进去的.
|