post请求时2种传参方式

本文探讨了在Java中使用POST请求时的两种参数传递方式,特别是通过JSON格式进行数据传输的方法。详细解释了如何将Java对象转换为JSON,并将其作为请求体发送到服务器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@Test
public void dopost(){
String httpurl = "https://jin.caimao.com/api/user/loginSalt";
Map<String,String> params = new HashMap<String,String>();
params.put("mobile", "XXXX");
params.put("login_pwd", "XXXX");
Editmappost(httpurl,params);
}
public void Editmappost(String url,Map<String,String> map){
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
List<NameValuePair> pair = new ArrayList<NameValuePair>();
for(Map.Entry<String, String> entry:map.entrySet()){
pair.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString()));
}
try {
httppost.setEntity(new UrlEncodedFormEntity(pair));

try {

CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if(response.getStatusLine().getStatusCode()==200){
String stringentity = EntityUtils.toString(entity);
System.out.println(stringentity);
}

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

@Test
public void dojsonpost(){
String apiurl = "http://baoxian.qa.ms.netease.com/vehicle";
String params = "{'license_no':'212','license_owner':'adfa','city_code':'21212'}";
JSONObject jsonobject = JSONObject.fromObject(params);
Editjsonpost(apiurl,jsonobject);
}
public void Editjsonpost(String url,Object json){
// JsonObject sjson = {"mobile":"XXXX","login_pwd":"XXXX"};
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);

StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8");
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");

httppost.setEntity(stringEntity);

try {

CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine().getStatusCode());
if(response.getStatusLine().getStatusCode()==200){
String stringentity = EntityUtils.toString(entity);
System.out.println(stringentity);
}

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}


}

转载于:https://www.cnblogs.com/wxjtest/p/6289077.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值