我有以下C#代码,我希望有一个与此相当的Java代码。以下C#代码来自this answer to another StackOverflow question。
代码如下:
string orkutSite = "http://www.orkut.com/Login.aspx"; // enter correct address
string formPage = "";
string afterLoginPage = "";
// Get postback data and cookies
CookieContainer cookies = new CookieContainer();
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(orkutSite);
getRequest.CookieContainer = cookies;
getRequest.Method = "GET";
HttpWebResponse form = (HttpWebResponse)getRequest.GetResponse();
using (StreamReader response =
new StreamReader(form.GetResponseStream(), Encoding.UTF8))
{
formPage = response.ReadToEnd();
}
Dictionary<string, string> inputs = new Dictionary<string,string>();
inputs.Add("__EVENTTARGET", "");
inputs.Add("__EVENTARGUMENT", "");
foreach (Match input in
Regex.Matches(formPage,
@"<input.*?name=""(?<name>.*?)"".*?(?:value=""(?<value>.*?)"".*?)? />",
RegexOptions.IgnoreCase | RegexOptions.ECMAScript))
{
inputs.Add(input.Groups["name"].Value, input.Groups["value"].Value);
}
inputs["username"] = "xxxxx"; // *please*, check for \\
inputs["password"] = "yyyyy"; // correct field names \\
byte[] buffer =
Encoding.UTF8.GetBytes(
String.Join("&",
Array.ConvertAll<KeyValuePair<string, string>, string(
inputs.ToArray(),
delegate(KeyValuePair item)
{
return item.Key + "=" + HttpUtility.UrlEncode(item.Value);
})));
HttpWebRequest postRequest = (HttpWebRequest)WebRequest.Create(orkutSite);
postRequest.CookieContainer = cookies;postRequest.Method = "POST";
postRequest.ContentType = "application/x-www-form-urlencoded";
// send username/password
using (Stream stream = postRequest.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
}
// get response from login page
using (StreamReader reader = new StreamReader(
postRequest.GetResponse().GetResponseStream(), Encoding.UTF8))
{
afterLoginPage = reader.ReadToEnd();
}
答案 0 :(得分:4)
我不打算为你转换这段代码的工作,但我可以为你提供一些帮助来开始。您列出的代码执行HTTP GET和POST,其中包含大量转换。乍看之下不确定它正在做什么或为什么会这样做。
我怀疑你可以用Java中的Apache Commons HttpClient等更高级别的库来替换它。它是一个非常强大的库,用于执行相同类型的操作,并且比Java中的简单URLConnection更直观。
他们有一个很好的tutorial和使用客户端的样本。如果您使用此客户端,则可能会减少样本中的转换代码。