用java模拟curl ( by quqi99 )

用java模拟curl ( by quqi99 )

// register user
StringBuffer postDataSb = new StringBuffer();
String formName = request.getParameter("form-name");
postDataSb.append("form-name=" + formName + "&");
Map<String, String> parameterMap = customRequest.getParameterMap();
if (parameterMap != null)
{
for (Map.Entry<String, String> entry : parameterMap.entrySet())
{
String key = entry.getKey();
if (key != null && key.startsWith(formName))
{
String val = entry.getValue();
postDataSb.append(key + "=" + URLEncoder.encode(val, "utf-8") + "&");
}
}
}
String liteRegUrl = "/" + LITE_REG_SERVLET;
URL reconstructedURL = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), liteRegUrl);
liteRegUrl = reconstructedURL.toString();

Map<String, String> requestHeaderMap = new HashMap<String, String>();
Cookie[] cookies = request.getCookies();
if (cookies != null)
{
StringBuffer cookieSb = new StringBuffer();
int size = cookies.length;
int count = 0;
for (Cookie cookie : cookies)
{
if (++count == size)
{
cookieSb.append(cookie.getName() + "=" + cookie.getValue());
}
else
{
cookieSb.append(cookie.getName() + "=" + cookie.getValue() + ";");
}
}
requestHeaderMap.put("Cookie", cookieSb.toString());
}
requestHeaderMap.put("Connection", "Keep-Alive");
requestHeaderMap.put("Host", reconstructedURL.getHost());
requestHeaderMap.put("Cache-Control", "no-cache");
requestHeaderMap.put("Content-Length", new Integer(postDataSb.length()).toString());
requestHeaderMap.put("Content-Type", "application/x-www-form-urlencoded");
String responseContent = null;
String result = curl(liteRegUrl, postDataSb.toString(), requestHeaderMap, true,null,null);
if (!Utils.isEmptyString(result))
{
String[] arrs = result.split("\r\n\r\n");
// forward cookie
if (arrs != null && arrs.length == 2)
{
String headers = arrs[0];
responseContent = arrs[1];
if (!Utils.isEmptyString(headers))
{
String[] headerArr = headers.split("\r\n");
for (String header : headerArr)
{
int pos = header.indexOf(":");
if (pos != -1)
{
String order = header.substring(0, pos);
String val = header.substring(pos + 1);
if ("Set-Cookie".equals(order) && !Utils.isEmptyString(val))
{
int pos2 = val.indexOf("=");
if (pos2 != -1)
{
String cookieName = val.substring(0, pos2);
String cookieVal = val.substring(pos2 + 1);
cookieVal = cookieVal.split(";")[0];
Cookie cookie = new Cookie(cookieName, cookieVal );
cookie.setPath("/");
cookie.setMaxAge(CookieManager.N_SESSION_COOKIE);
String cookieDomain = CookieManager.getCookieDomain();
if (cookieDomain != null)
{
cookie.setDomain(cookieDomain);
}
response.addCookie(cookie);
}
}
}
}
}
}
}

public static String curl(String postUrl, String postData, Map<String, String> requestHeaderMap, boolean isReturnHeader, String basicAuthUser, String basicAuthPass)
{
String result = "";
HttpURLConnection httpUrlConnection = null;
boolean foundRedirect = false;
try
{
String _basicAuth = null;
if (basicAuthUser != null && basicAuthPass != null)
{
sun.misc.BASE64Encoder base64 = new sun.misc.BASE64Encoder();
_basicAuth = "Basic " + base64.encode((basicAuthUser + ":" + basicAuthPass).getBytes());
}
URL url = new URL(postUrl);
do
{
URLConnection urlConnection = url.openConnection();
httpUrlConnection = (HttpURLConnection) urlConnection;
HttpURLConnection.setFollowRedirects(true);
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
httpUrlConnection.setConnectTimeout(3000);
httpUrlConnection.setReadTimeout(3000);
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setDefaultUseCaches(false);
httpUrlConnection.setRequestMethod("POST");
if (_basicAuth != null)
{
httpUrlConnection.setRequestProperty("Authorization", _basicAuth);
}
httpUrlConnection
.setRequestProperty("User-Agent",
"User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13");
httpUrlConnection
.setRequestProperty(
"Accept",
"image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*");
// set request header
if (requestHeaderMap != null)
{
for (Map.Entry<String, String> entry : requestHeaderMap.entrySet())
{
String key = entry.getKey();
String val = entry.getValue();
if (key != null && val != null)
{
httpUrlConnection.setRequestProperty(key, val);
}
}
}
httpUrlConnection.connect();
OutputStream os = httpUrlConnection.getOutputStream();
os.write(postData.getBytes("utf-8"));
os.flush();
os.close();
int responseCode = httpUrlConnection.getResponseCode();
BufferedReader br = null;
if (responseCode == 302)
{
String location = urlConnection.getHeaderField("Location");
url = new URL(location);
foundRedirect = true;
}
else if (responseCode == 200 || responseCode == 201)
{
br = new BufferedReader(new InputStreamReader(new BufferedInputStream(httpUrlConnection
.getInputStream()), "utf-8"));
}
else
{
br = new BufferedReader(new InputStreamReader(new BufferedInputStream(httpUrlConnection
.getErrorStream()), "utf-8"));
}
// get content
StringBuffer contentSb = new StringBuffer("");
String strLine = null;
while ((strLine = br.readLine()) != null)
{
contentSb.append(strLine + "\r\n");
}
br.close();
result = contentSb.toString();
// get response header
if (isReturnHeader)
{
Map<String, List<String>> responseHeaderMap = httpUrlConnection.getHeaderFields();
if (responseHeaderMap != null)
{
StringBuffer responseHeaderSb = new StringBuffer();
for (Map.Entry<String, List<String>> entry : responseHeaderMap.entrySet())
{
String key = entry.getKey();
List<String> valList = entry.getValue();
if (!Utils.isEmptyString(key) && valList != null)
{
for (String val : valList)
{
if (!Utils.isEmptyString(val))
{
responseHeaderSb.append(key + ":" + val + "\r\n");
}
}
}
}
if (responseHeaderSb.toString().endsWith("\r\n"))
{
result = responseHeaderSb.toString() + "\r\n" + result;
}
else
{
result = responseHeaderSb.toString() + "\r\n\r\n" + result;
}
}
}
}
while (foundRedirect);
}
catch (Exception e)
{
Logging.SERVLET.debug("Cannot load URL: " + e.getMessage());
return null;
}
finally
{
if (httpUrlConnection != null)
{
httpUrlConnection.disconnect();
}
}
return result;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值