Python form submit


    public static String
            doSubmit(String url, HashMap<String, String> data)
            throws UnsupportedEncodingException, IOException {
        URL siteUrl = new URL(url);
        HttpURLConnection conn =
                (HttpURLConnection) siteUrl.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);

        DataOutputStream out =
                new DataOutputStream(conn.getOutputStream());

        Set<String> keys = data.keySet();
        Iterator<String> keyIter = keys.iterator();
        String content = "";
        for (int i = 0; keyIter.hasNext(); i++) {
            String key = keyIter.next();
            if (i != 0) {
                content += "&";
            }
            content += key + "=" +
                    URLEncoder.encode(data.get(key), "UTF-8");
        }
        //System.out.println(content);
        out.writeBytes(content);
        out.flush();
        out.close();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
        String line = "";
        StringBuilder result = new StringBuilder();
        while ((line = in.readLine()) != null) {
               result.append(line);
        }
        in.close();
        return result.toString();
    }
#!/usr/bin/env python

import urllib
import urllib2


class HttpBot:
    """an HttpBot represents one browser session, with cookies."""
    def __init__(self):
        cookie_handler= urllib2.HTTPCookieProcessor()
        redirect_handler= urllib2.HTTPRedirectHandler()
        self._opener = urllib2.build_opener(redirect_handler, cookie_handler)

    def GET(self, url):
        return self._opener.open(url).read()

    def POST(self, url, parameters):
        return self._opener.open(url, urllib.urlencode(parameters)).read()
if __name__ == "__main__":
    bot = HttpBot()
    result = bot.POST('http://localhost:8080/service/myform.jsp',
     {'username':'mossila', 'password':'1234})
    print result

Advertisements

One thought on “Python form submit

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s