httpclient请求接口
来源:互联网 发布:国产外设品牌知乎 编辑:程序博客网 时间:2024/04/28 04:20
1、打开外系统页面接口
A系统servlet 用双方约定的加密算法加密后,用httpclient调用对方服务,对方验证合法后打开页面
代码为A系统调用方法:
package com.ultrapower.alarmwiki;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import cn.com.ultrapower.system.util.FormatTime;
/**
* 测试各省调用接口类
*
* @author <a href="mailto:jiangtao@ultrapower.com.cn">jiangtao</a>
*
* @version $Revision$
*
* @since 2013-11-11
*/
public class AlarmWikiServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Log log = LogFactory.getLog("AlarmWikiServlet.class");
@Override
protected void service(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
String url = request.getParameter("alarmUrl");
String token = request.getParameter("token");
String key = request.getParameter("key");
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
String timestamp = FormatTime.formatIntToDateString(System.currentTimeMillis()/1000);
token = token + timestamp;
log.info("加密前url:" + url + ";token:" + token + ";key:" + key);
// 加密
try {
token = DataAES.encrypt(token, key);
} catch (Exception e) {
e.printStackTrace();
}
StringEntity entity = new StringEntity("token=" + token, "UTF-8");
entity.setContentType("application/x-www-form-urlencoded");
post.setEntity(entity);
log.info("---调用告警百科--");
HttpResponse httpResponse = client.execute(post);
response.getWriter().write(EntityUtils.toString(httpResponse.getEntity()));
}
}
加密算法:
package com.ultrapower.alarmwiki;
/*
* 文件名: DataAES.java
*
* 创建日期: 2013-11-28
*
* Copyright(C) 2013, by jiangtao.
*
* 原始作者: <a href="mailto:jiangtao@ultrapower.com.cn">jiangtao</a>
*
*/
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import com.thoughtworks.xstream.core.util.Base64Encoder;
/**
* 数据AES加解密算法公用类
*
* @author <a href="mailto:jiangtao@ultrapower.com.cn">jiangtao</a>
*
* @version $Revision$
*
* @since 2013-11-28
*/
public class DataAES {
/**
* 加密--把加密后的byte数组先进行二进制转16进制在进行base64编码
*
* @param sSrc
* @param sKey
* @return
* @throws Exception
*/
public static String encrypt(String sSrc, String sKey) throws Exception {
if (sKey == null) {
throw new IllegalArgumentException("Key为空null.");
}
if (sKey.length() != 16) {
throw new IllegalArgumentException("Key长度不是16位.");
}
// 算法
byte[] raw = sKey.getBytes("UTF-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// 创建密码器
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));
String tempStr = parseByte2HexStr(encrypted);
//此处使用BASE64做转码功能,同时能起到2次加密的作用。
Base64Encoder encoder = new Base64Encoder();
return encoder.encode(tempStr.getBytes("UTF-8"));
}
/**
* 解密--先 进行base64解码,在进行16进制转为2进制然后再解码
*
* @param sSrc
* @param sKey
* @return
* @throws Exception
*/
public static String decrypt(String sSrc, String sKey) throws Exception {
if (sKey == null) {
throw new IllegalArgumentException("Key为空null");
}
if (sKey.length() != 16) {
throw new IllegalArgumentException("Key长度不是16位");
}
byte[] raw = sKey.getBytes("UTF-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
//先用base64解密
Base64Encoder encoder = new Base64Encoder();
byte[] encrypted1 = encoder.decode(sSrc);
String tempStr = new String(encrypted1, "UTF-8");
encrypted1 = parseHexStr2Byte(tempStr);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "UTF-8");
return originalString;
}
/**
* 将二进制转换成16进制
*
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 将16进制转换为二进制
*
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
public static void main(String args[]){
String strs = "SD;FMS;589398413;gongqin@sd.chinamobile.com,2013-11-28 09:59:35";
String key = "1c3b72258919d5ce";
String encrypt = "";
String decrypt = "N0U2MDEyQzc3NkUyOTRDMDEyMEFDRkM2MDQxODZBRDY2NEVEMjcyRTU1NzI0QjEyNjQzODIxRDc2QzgwREI1MzNBMUU5MTJCRUI1OUYyRjU2MTU4NjJEQjhDM0I1RjBCRUI3NjQ0QjQ1MkQ0ODE4MUExQkMwQkE2NkRDRUE1REE=";
try {
encrypt = encrypt(strs, key);
System.out.println("###encrypt==" + encrypt);
decrypt = decrypt(decrypt, key);
System.out.println("###decrypt==" + decrypt);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2、获取响应头消息
A系统通过httpclient 调用外系统servlet ,获取返回的响应头消息
package com.ultrapower.eoms.common.cas;
import com.remedy.arsys.config.Configuration;
import com.remedy.arsys.session.Authenticator;
import com.remedy.arsys.session.UserCredentials;
import com.ultrapower.eoms.common.util.CryptUtils;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
public class EomsAuthenticator
implements Authenticator
{
private static String LOGIN_URL;
private static String SSO_URL;
private static String COOKIE_NAME = "EOMS_ID";
private CryptUtils cp;
public void destroy()
{
}
public UserCredentials getAuthenticatedCredentials(HttpServletRequest req, HttpServletResponse resp)
throws IOException
{
String eomsid = req.getParameter(COOKIE_NAME);
if ((eomsid == null) || ("".equals(eomsid))) {
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
if (COOKIE_NAME.equals(c.getName())) {
eomsid = c.getValue();
break;
}
}
}
}
if (eomsid == null) {
redirectToLogin(req, resp);
return null;
}
String url = req.getScheme() + "://" + req.getServerName() + ":" +
req.getServerPort() + SSO_URL;
PostMethod pe = new PostMethod(url);
try {
pe.setRequestBody(new NameValuePair[] {
new NameValuePair("eomsid",
eomsid) });
HttpClient client = new HttpClient();
int code = client.executeMethod(pe);
String key1 = null;
String key2 = null;
if (code == 200) {
key1 = pe.getResponseHeader("key1").getValue();
key2 = pe.getResponseHeader("key2").getValue();
key1 = this.cp.decode(key1);
if ((key1 == null) || ("".equals(key1))) {
redirectToLogin(req, resp);
return null;
}
String key2 = this.cp.decode(key2);
UserCredentials localUserCredentials = new UserCredentials(key1, key2, null);
return localUserCredentials;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
pe.releaseConnection(); } pe.releaseConnection();
return null;
}
public static void redirectToLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException
{
String url = req.getScheme() + "://" + req.getServerName() + ":" +
req.getServerPort() + LOGIN_URL;
resp.sendRedirect(url);
}
public void init(Map map) {
Configuration config = Configuration.getInstance();
LOGIN_URL = config.getProperty("eoms.login.url");
SSO_URL = config.getProperty("eoms.sso.url");
String key = config.getProperty("eoms.sso.enckey");
this.cp = CryptUtils.getInstance(new String[] { key });
}
}
- httpclient请求接口
- Http请求接口HttpClient
- httpClient 设置代理请求接口
- java HttpClient get post请求 调用接口
- httpClient发送get请求调用接口
- 【接口测试】:HttpClient Post 和 Get 请求
- HttpClient请求接口上传文件以及参数
- HttpClient get请求调取接口 例子
- HttpClient post请求调取接口 例子
- 接口自动化之httpclient发get请求、post请求
- 调用图片上传http接口,利用httpClient模拟请求
- 利用HTTPClient模块中HttpGet和HttpPost 发送接口请求
- 使用HttpClient请求另一个项目接口获取内容
- [随记] 使用httpClient发送post请求连接restful接口
- 使用HttpClient请求另一个项目接口获取内容
- 使用httpclient模拟http请求其他系统的接口
- HttpClient请求
- HttpClient请求
- iOS之clang: error: linker command failed with exit code 1 (use -v to see invocation)
- ANDROID_DAILY_OVERRIDE 的Gradle问题
- android开发退出应用方法
- 一句话概括下spring框架及spring cloud框架主要组件
- v540 检测的问题
- httpclient请求接口
- Python 中 os 模块使用方法
- filebeat常见配置整理
- Python源码理解: '+=' 和 'xx = xx + xx'的区别
- mysql5.6配置版本,无法启动,报错1067
- Android启动优化,去除白屏或者黑屏
- C++中string转为char *
- eclipse运行错误提示 Failed to load D:\Android\sdk\build-tools\26.0.0-preview\lib\dx.jar Unknown error: Un
- json-path 解析json 类似xpath 超好用