使用HttpClient的POST方式传JSON格式的参数给Restful服务

  • Post author:
  • Post category:其他



需要支持的JAR包:


httpclient-4.2.5,httpcore-4.3


1、Android/java:

JSONObject jsonObj = new JSONObject();

jsonObj.put(“userName “, userName);

jsonObj.put(“passWord”, passWord);

// Create the POST object and add the parameters

HttpPost httpPost = new HttpPost(url);

StringEntity entity = new StringEntity(jsonObj.toString(), “UTF-8”);

entity.setContentType(“application/json”);

httpPost.setEntity(entity);

HttpClient client = new DefaultHttpClient();

HttpResponse response = client.execute(httpPost);


2、用jQuery:

var data = {};

data.userName = “zhangsan”;

data.passWord= “12345”;

var myData=$.toJSON(data);

$.ajax({

url:url,

type:”POST”,

data:myData,

contentType:”application/json; charset=utf-8″,

dataType:”json”,

success: function(){

}

})



版权声明:本文为iteye_8401原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。