public static void main(String[] args) {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(URL);
// 创建参数队列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
//设置请求参数
formparams.add(new BasicNameValuePair("userName", userName));
formparams.add(new BasicNameValuePair("password", password));
formparams.add(new BasicNameValuePair("pwd",pwd ));
formparams.add(new BasicNameValuePair("encrypt", encrypt));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
// 调用setParams、setEntity设置请求参数
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
// 发送请求,接受响应
CloseableHttpResponse response = httpclient.execute(httppost);
System.out.println("响应行和响应头"+response.toString());
try {
// 获取响应的响应体
HttpEntity entity = response.getEntity();
if (entity != null) {
JSONObject json = JSONObject.fromObject(EntityUtils.toString(entity, "UTF-8"));
String result = json.getString("result");
String msg = json.getString("msg");
System.out.println("result:"+result);
System.out.println("msg:"+msg);
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}