post请求时2种传参方式

@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();
}


}


}
posted @ 2017-01-16 11:51  wxjhappy  阅读(10284)  评论(0编辑  收藏  举报