tags:

views:

322

answers:

1

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();
}
+2  A: 

I'm not going to do the work of converting this piece of code for you, but I can provide you with some help to get started. The code you listed does an HTTP GET and a POST with a whole ton of conversions going on in there. Not sure exactly all of what it is doing or why at first glance.

I suspect you can replace a lot of that with a higher level library like the Apache Commons HttpClient in Java. It is a very powerful library for doing this same sort of thing and is more intuitive than a simple URLConnection in Java.

They have a good tutorial and samples on using the client. If you use this client, you can probably get away with a lot less of the conversion code that is in your sample.

Chris Dail