I have the following C# code and I want to have a Java code equivalent to this. The following C# code is from this answer to another StackOverflow question.
The code is as follows:
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();
}