public String connectServer(Object inputObject, String serverURL) {
String result = "";
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(serverURL);
ArrayList<NameValuePair> nvpairs = new ArrayList<NameValuePair>();
nvpairs.add(new BasicNameValuePair("agencyClientCode", "123"));
nvpairs.add(new BasicNameValuePair("name", "huaan"));
nvpairs.add(new BasicNameValuePair("password", "huaan123!@#"));
nvpairs.add(new BasicNameValuePair("xml", inputObject.toString()));
Mcrypt mcrypt = new MD5Mcrypt("UTF-8", "123!@#");
String mcryptStr = mcrypt.encode(inputObject.toString());
System.out.println(mcryptStr);
nvpairs.add(new BasicNameValuePair("sign", mcryptStr));
httppost.setEntity(new UrlEncodedFormEntity(nvpairs, "UTF-8"));
response = httpclient.execute(httppost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity resEntity = response.getEntity();
result = URLDecoder.decode(EntityUtils.toString(resEntity), "UTF-8");
} else {
throw new IllegalStateException("Method failed: " + response.getStatusLine());
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
前提使用:httpclient.jar和httpcore.jar包。
1:NameValuePair是简单名称节点类型,主要表达形式是键值对的表达形式。
2:通过new 一个带URL服务的httppost对象和要存储的数据,再通过httpclient的execute方法把数据传递到所对应的服务上来实现数据的交互。<pre name="code" class="java">statusCode 如返回200代码表示成功,404表示服务路径错误。
3上述还用到java自带的MD5算法。MD5算法是不可逆的,本代码是将数据转化为16进制进行的加密处理,对数据进行加密处理的过程中此算法使用最为广泛,当然还有其他算法包括MD2,MD4,SHA-1,通常使用最多的也就是MD5和SHA-1,SHA-1听说有美国安全局的背景,对于阴谋论者,觉得处于安全性上的考虑还是MD5较好,而且MD5速度比SHA-1快接近1倍。没什么理由不去选择MD5咯。