用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 parameterMap = customRequest.getParameterMap();
if (parameterMap != null)
{
for (Map.Entry 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 requestHeaderMap = new HashMap();
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 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 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> responseHeaderMap = httpUrlConnection.getHeaderFields();
if (responseHeaderMap != null)
{
StringBuffer responseHeaderSb = new StringBuffer();
for (Map.Entry> entry : responseHeaderMap.entrySet())
{
String key = entry.getKey();
List 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;
}

你可能感兴趣的:(用java模拟curl ( by quqi99 ))