Example usage for org.apache.commons.httpclient.methods PostMethod setRequestBody

List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestBody

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods PostMethod setRequestBody.

Prototype

public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException 

Source Link

Usage

From source file:pl.umk.mat.zawodyweb.compiler.classes.LanguageLA.java

private void logIn(String login, String password) throws HttpException, IOException {
    ArrayList<NameValuePair> vectorLoginData;
    GetMethod get = new GetMethod(acmSite);

    try {/*from   w  w  w . j av a  2  s  . c  o m*/
        client.executeMethod(get);
        InputStream firstGet = get.getResponseBodyAsStream();
        BufferedReader br;

        try {
            br = new BufferedReader(new InputStreamReader(firstGet, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            logger.error("UnsupportedEncodingException ", e);
            return;
        }

        String line, name, value;
        vectorLoginData = new ArrayList<NameValuePair>();
        vectorLoginData.add(new NameValuePair("username", login));
        vectorLoginData.add(new NameValuePair("passwd", password));

        line = br.readLine();
        while (line != null && !line.matches(".*class=\"mod_login\".*")) {
            line = br.readLine();
        }
        while (line != null && !line.matches("(?i).*submit.*login.*")) {
            if (line.matches(".*hidden.*name=\".*value=\".*")) {
                name = line.split("name=\"")[1].split("\"")[0];
                value = line.split("value=\"")[1].split("\"")[0];
                vectorLoginData.add(new NameValuePair(name, value)); // FIXME: check if it's neccesary: URLDecoder.decode(value, "UTF-8"));
            }
            line = br.readLine();
        }
    } finally {

        get.releaseConnection();
    }
    vectorLoginData.add(new NameValuePair("remember", "yes"));
    vectorLoginData.add(new NameValuePair("Submit", "Login"));

    PostMethod post = new PostMethod(acmSite + "index.php?option=com_comprofiler&task=login");
    post.setRequestHeader("Referer", acmSite);
    NameValuePair[] loginData = new NameValuePair[0];
    loginData = vectorLoginData.toArray(loginData);
    post.setRequestBody(loginData);

    client.executeMethod(post);

    post.releaseConnection();
}

From source file:pl.umk.mat.zawodyweb.compiler.classes.LanguageLA.java

private String sendSolution(String code, TestInput input) throws HttpException, IOException {
    PostMethod post = new PostMethod(
            acmSite + "index.php?option=com_onlinejudge&Itemid=25&page=save_submission");
    try {/*from   ww  w .  j av a 2  s.c om*/

        String langId = properties.getProperty("uva.languageId");
        if (langId != null) {
            if (langId.equals("1") || langId.equalsIgnoreCase("C")) {
                langId = "1";
            } else if (langId.equals("2") || langId.equalsIgnoreCase("JAVA")) {
                langId = "2";
            } else if (langId.equals("3") || langId.equalsIgnoreCase("C++")) {
                langId = "3";
            } else if (langId.equals("4") || langId.equalsIgnoreCase("PASCAL")) {
                langId = "4";
            } else if (langId.equals("5") || langId.equalsIgnoreCase("C++11")) {
                langId = "5";
            } else {
                langId = null;
            }
        }

        if (langId == null) {
            String fileExt = properties.getProperty("CODEFILE_EXTENSION");
            if (fileExt.equals("c")) {
                langId = "1";
            } else if (fileExt.equals("java")) {
                langId = "2";
            } else if (fileExt.equals("cpp")) {
                langId = "3";
            } else if (fileExt.equals("pas")) {
                langId = "4";
            } else if (fileExt.equals("cpp11")) {
                langId = "5";
            }
        }
        NameValuePair[] dataSendAnswer = { new NameValuePair("problemid", ""),
                new NameValuePair("category", ""), new NameValuePair("localid", input.getInputText()),
                new NameValuePair("language", langId), new NameValuePair("code", code),
                new NameValuePair("submit", "Submit") };
        post.setRequestBody(dataSendAnswer);

        client.executeMethod(post);
        String location = post.getResponseHeader("Location").getValue();

        String msg = location.substring(location.lastIndexOf("msg=") + 4);
        if (msg.contains("Submission+received")) {
            return msg.substring(msg.lastIndexOf("+") + 1);
        } else {
            return java.net.URLDecoder.decode(msg, "UTF-8");
        }
    } finally {
        post.releaseConnection();
    }
}

From source file:pl.umk.mat.zawodyweb.compiler.classes.LanguageLA.java

private void logOut() throws HttpException, IOException {
    PostMethod post = new PostMethod(acmSite + "index.php?option=logout");
    try {/*from  w  w  w. ja  va  2s .c o m*/
        NameValuePair[] logout = { new NameValuePair("op2", "logout"), new NameValuePair("return", acmSite),
                new NameValuePair("lang", "english"), new NameValuePair("message", "0"),
                new NameValuePair("Submit", "Logout") };
        post.setRequestBody(logout);

        client.executeMethod(post);
    } finally {
        post.releaseConnection();
    }
}

From source file:pl.umk.mat.zawodyweb.compiler.classes.LanguageMAIN.java

/**
 * Sprawdza rozwizanie na input// w ww .j a  v  a2  s.c om
 * @param path kod rdowy
 * @param input w formacie:
 *              <pre>c=NUMER_KONKURSU<br/>t=NUMER_ZADANIA<br/>m=MAX_POINTS</pre>
 * @return
 */
@Override
public TestOutput runTest(String path, TestInput input) {
    TestOutput result = new TestOutput(null);

    Integer contest_id = null;
    Integer task_id = null;
    Integer max_points = null;
    try {
        try {
            Matcher matcher = null;

            matcher = Pattern.compile("c=([0-9]+)").matcher(input.getInputText());
            if (matcher.find()) {
                contest_id = Integer.valueOf(matcher.group(1));
            }

            matcher = Pattern.compile("t=([0-9]+)").matcher(input.getInputText());
            if (matcher.find()) {
                task_id = Integer.valueOf(matcher.group(1));
            }

            matcher = Pattern.compile("m=([0-9]+)").matcher(input.getInputText());
            if (matcher.find()) {
                max_points = Integer.valueOf(matcher.group(1));
            }

            if (contest_id == null) {
                throw new IllegalArgumentException("task_id == null");
            }
            if (task_id == null) {
                throw new IllegalArgumentException("task_id == null");
            }
        } catch (PatternSyntaxException ex) {
            throw new IllegalArgumentException(ex);
        } catch (NumberFormatException ex) {
            throw new IllegalArgumentException(ex);
        } catch (IllegalStateException ex) {
            throw new IllegalArgumentException(ex);
        }
    } catch (IllegalArgumentException e) {
        logger.error("Exception when parsing input", e);
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(e.getMessage());
        result.setOutputText("MAIN IllegalArgumentException");
        return result;
    }
    logger.debug("Contest id = " + contest_id);
    logger.debug("Task id = " + task_id);
    logger.debug("Max points = " + max_points);

    String loginUrl = "http://main.edu.pl/pl/login";
    String login = properties.getProperty("main_edu_pl.login");
    String password = properties.getProperty("main_edu_pl.password");

    HttpClient client = new HttpClient();

    HttpClientParams params = client.getParams();
    params.setParameter("http.useragent", "Opera/9.64 (Windows NT 6.0; U; pl) Presto/2.1.1");
    //params.setParameter("http.protocol.handle-redirects", true);
    client.setParams(params);
    /* logowanie */
    logger.debug("Logging in");
    PostMethod postMethod = new PostMethod(loginUrl);
    NameValuePair[] dataLogging = { new NameValuePair("auth", "1"), new NameValuePair("login", login),
            new NameValuePair("pass", password) };
    postMethod.setRequestBody(dataLogging);
    try {
        client.executeMethod(postMethod);
        if (Pattern.compile("Logowanie udane").matcher(postMethod.getResponseBodyAsString(1024 * 1024))
                .find() == false) {
            logger.error("Unable to login (" + login + ":" + password + ")");
            result.setStatus(ResultsStatusEnum.UNDEF.getCode());
            result.setOutputText("Logging in failed");
            postMethod.releaseConnection();
            return result;
        }
    } catch (HttpException e) {
        logger.error("Exception when logging in", e);
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(e.getMessage());
        result.setOutputText("HttpException");
        postMethod.releaseConnection();
        return result;
    } catch (IOException e) {
        logger.error("Exception when logging in", e);
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(e.getMessage());
        result.setOutputText("IOException");
        postMethod.releaseConnection();
        return result;
    }
    postMethod.releaseConnection();

    /* wchodzenie na stron z wysyaniem zada i pobieranie pl z hidden */
    logger.debug("Getting submit page");
    ArrayList<Part> values = new ArrayList<Part>();
    try {
        GetMethod getMethod = new GetMethod("http://main.edu.pl/user.phtml?op=submit&m=insert&c=" + contest_id);
        client.executeMethod(getMethod);
        String response = getMethod.getResponseBodyAsString(1024 * 1024);
        getMethod.releaseConnection();

        Matcher tagMatcher = Pattern.compile("<input[^>]*>").matcher(response);
        Pattern namePattern = Pattern.compile("name\\s*=\"([^\"]*)\"");
        Pattern valuePattern = Pattern.compile("value\\s*=\"([^\"]*)\"");
        while (tagMatcher.find()) {
            Matcher matcher = null;
            String name = null;
            String value = null;

            String inputTag = tagMatcher.group();

            matcher = namePattern.matcher(inputTag);
            if (matcher.find()) {
                name = matcher.group(1);
            }

            matcher = valuePattern.matcher(inputTag);
            if (matcher.find()) {
                value = matcher.group(1);
            }

            if (name != null && value != null && name.equals("solution") == false) {
                values.add(new StringPart(name, value));
            }
        }
    } catch (HttpException ex) {
        logger.error("Exception when getting submit page", ex);
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(ex.getMessage());
        result.setOutputText("IOException");
        return result;
    } catch (IOException ex) {
        logger.error("Exception when getting submit page", ex);
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(ex.getMessage());
        result.setOutputText("IOException");
        return result;
    }

    values.add(new StringPart("task", task_id.toString()));

    String filename = properties.getProperty("CODE_FILENAME");
    filename = filename.replaceAll("\\." + properties.getProperty("CODEFILE_EXTENSION") + "$", "");
    filename = filename + "." + properties.getProperty("CODEFILE_EXTENSION");
    FilePart filePart = new FilePart("solution", new ByteArrayPartSource(filename, path.getBytes()));
    values.add(filePart);

    /* wysyanie rozwizania */
    logger.debug("Submiting solution");
    Integer solution_id = null;
    postMethod = new PostMethod("http://main.edu.pl/user.phtml?op=submit&m=db_insert&c=" + contest_id);
    postMethod.setRequestEntity(new MultipartRequestEntity(values.toArray(new Part[0]), client.getParams()));
    try {
        try {
            client.executeMethod(postMethod);
            HttpMethod method = postMethod;

            /* check if redirect */
            Header locationHeader = postMethod.getResponseHeader("location");
            if (locationHeader != null) {
                String redirectLocation = locationHeader.getValue();
                GetMethod getMethod = new GetMethod(
                        new URI(postMethod.getURI(), new URI(redirectLocation, false)).getURI());
                client.executeMethod(getMethod);
                method = getMethod;
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            Matcher matcher = Pattern.compile("<tr id=\"rptr\">.*?</tr>", Pattern.DOTALL)
                    .matcher(sb.toString());
            if (matcher.find()) {
                Matcher idMatcher = Pattern.compile("id=([0-9]+)").matcher(matcher.group());
                if (idMatcher.find()) {
                    solution_id = Integer.parseInt(idMatcher.group(1));
                }
            }
            if (solution_id == null) {
                throw new IllegalArgumentException("solution_id == null");
            }
        } catch (HttpException e) {
            new IllegalArgumentException(e);
        } catch (IOException e) {
            new IllegalArgumentException(e);
        } catch (NumberFormatException e) {
            new IllegalArgumentException(e);
        } catch (IllegalStateException e) {
            new IllegalArgumentException(e);
        }

    } catch (IllegalArgumentException e) {
        logger.error("Exception when submiting solution", e);
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(e.getMessage());
        result.setOutputText("IllegalArgumentException");
        postMethod.releaseConnection();
        return result;
    }

    postMethod.releaseConnection();

    /* sprawdzanie statusu */
    logger.debug("Checking result for main.id=" + solution_id);
    Pattern resultRowPattern = Pattern.compile("id=" + solution_id + ".*?</tr>", Pattern.DOTALL);
    Pattern resultPattern = Pattern.compile(
            "</td>.*?<td.*?>.*?</td>.*?<td.*?>(.*?)</td>.*?<td.*?>.*?</td>.*?<td.*?>(.*?)</td>",
            Pattern.DOTALL);
    result_loop: while (true) {
        try {
            Thread.sleep(7000);
        } catch (InterruptedException e) {
            result.setStatus(ResultsStatusEnum.UNDEF.getCode());
            result.setNotes(e.getMessage());
            result.setOutputText("InterruptedException");
            return result;
        }

        GetMethod getMethod = new GetMethod("http://main.edu.pl/user.phtml?op=zgloszenia&c=" + contest_id);
        try {
            client.executeMethod(getMethod);
            String response = getMethod.getResponseBodyAsString(1024 * 1024);
            getMethod.releaseConnection();

            Matcher matcher = resultRowPattern.matcher(response);
            // "</td>.*?<td.*?>.*?[NAZWA_ZADANIA]</td>.*?<td.*?>(.*?[STATUS])</td>.*?<td.*?>.*?</td>.*?<td.*?>(.*?[PUNKTY])</td>"
            while (matcher.find()) {
                Matcher resultMatcher = resultPattern.matcher(matcher.group());

                if (resultMatcher.find() && resultMatcher.groupCount() == 2) {
                    String resultType = resultMatcher.group(1);
                    if (resultType.equals("?")) {
                        continue;
                    } else if (resultType.matches("B..d kompilacji")) { // CE
                        result.setStatus(ResultsStatusEnum.CE.getCode());
                        result.setPoints(
                                calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points));
                    } else if (resultType.matches("Program wyw.aszczony")) { // TLE
                        result.setStatus(ResultsStatusEnum.TLE.getCode());
                        result.setPoints(
                                calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points));
                    } else if (resultType.matches("B..d wykonania")) { // RTE
                        result.setStatus(ResultsStatusEnum.RE.getCode());
                        result.setPoints(
                                calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points));
                    } else if (resultType.matches("Z.a odpowied.")) { // WA
                        result.setStatus(ResultsStatusEnum.WA.getCode());
                        result.setPoints(
                                calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points));
                    } else if (resultType.equals("OK")) { // AC
                        result.setStatus(ResultsStatusEnum.ACC.getCode());
                        result.setPoints(
                                calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points));
                    } else {
                        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
                        result.setNotes("Unknown status: \"" + resultType + "\"");
                    }
                    break result_loop;
                }
            }
        } catch (HttpException ex) {
            result.setStatus(ResultsStatusEnum.UNDEF.getCode());
            result.setNotes(ex.getMessage());
            result.setOutputText("HttpException");
            return result;
        } catch (IOException ex) {
            result.setStatus(ResultsStatusEnum.UNDEF.getCode());
            result.setNotes(ex.getMessage());
            result.setOutputText("IOException");
            return result;
        }
    }
    return result;
}

From source file:pl.umk.mat.zawodyweb.compiler.classes.LanguageOPSS.java

@Override
public TestOutput runTest(String path, TestInput input) {
    TestOutput result = new TestOutput(null);

    String loginUrl = "http://opss.assecobs.pl/?&login";
    String login = properties.getProperty("opss.login");
    String password = properties.getProperty("opss.password");

    HttpClient client = new HttpClient();

    HttpClientParams params = client.getParams();
    params.setParameter("http.useragent", "Opera/9.64 (Windows NT 6.0; U; pl) Presto/2.1.1");
    client.setParams(params);//  ww w .  ja  v  a  2 s.c om

    PostMethod logging = new PostMethod(loginUrl);
    NameValuePair[] dataLogging = { new NameValuePair("login_form_submit", "1"),
            new NameValuePair("login_form_login", login), new NameValuePair("login_form_pass", password) };
    logging.setRequestBody(dataLogging);
    try {
        client.executeMethod(logging);
    } catch (HttpException e) {
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(e.getMessage());
        result.setOutputText("HttpException");
        logging.releaseConnection();
        return result;
    } catch (IOException e) {
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(e.getMessage());
        result.setOutputText("IOException");
        logging.releaseConnection();
        return result;
    }
    logging.releaseConnection();
    PostMethod sendAnswer = new PostMethod("http://opss.assecobs.pl/?menu=comp&sub=send&comp=0");
    NameValuePair[] dataSendAnswer = { new NameValuePair("form_send_submit", "1"),
            new NameValuePair("form_send_comp", ""),
            new NameValuePair("form_send_problem", input.getInputText()),
            new NameValuePair("form_send_lang", properties.getProperty("CODEFILE_EXTENSION")),
            new NameValuePair("form_send_sourcetext", path),
            new NameValuePair("form_send_submittxt", "Wylij kod") };
    sendAnswer.setRequestBody(dataSendAnswer);
    InputStream status = null;
    try {
        client.executeMethod(sendAnswer);
        status = sendAnswer.getResponseBodyAsStream();
    } catch (HttpException e) {
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(e.getMessage());
        result.setOutputText("HttpException");
        sendAnswer.releaseConnection();
        return result;
    } catch (IOException e) {
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(e.getMessage());
        result.setOutputText("IOException");
        sendAnswer.releaseConnection();
        return result;
    }
    String submitId = null;
    BufferedReader br = null;
    try {
        br = new BufferedReader(new InputStreamReader(status, "iso-8859-2"));
    } catch (UnsupportedEncodingException e) {
    }
    String line;
    try {
        Pattern p = Pattern.compile("<a[^>]*href=[^>]*sub=stat[^>]*id=\\d*[^>]*>");
        line = br.readLine();
        Matcher m = p.matcher(line);
        while (!m.find() && line != null) {
            line = br.readLine();
            m = p.matcher(line);
        }
        Pattern p1 = Pattern.compile("id=\\d*");
        Matcher m1 = p1.matcher(m.group());
        m1.find();
        submitId = m1.group().split("=")[1];
    } catch (IOException e) {
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(e.getMessage());
        result.setOutputText("IOException");
        sendAnswer.releaseConnection();
        return result;
    }
    sendAnswer.releaseConnection();
    do {
        try {
            Thread.sleep(7000);
        } catch (InterruptedException e) {
            result.setStatus(ResultsStatusEnum.UNDEF.getCode());
            result.setNotes(e.getMessage());
            result.setOutputText("InterruptedException");
            return result;
        }
        GetMethod answer = new GetMethod("http://opss.assecobs.pl/?menu=comp&sub=stat&comp=0&id=" + submitId);
        InputStream answerStream = null;
        try {
            client.executeMethod(answer);
            answerStream = answer.getResponseBodyAsStream();
        } catch (HttpException e) {
            result.setStatus(ResultsStatusEnum.UNDEF.getCode());
            result.setNotes(e.getMessage());
            result.setOutputText("HttpException");
            answer.releaseConnection();
            return result;
        } catch (IOException e) {
            result.setStatus(ResultsStatusEnum.UNDEF.getCode());
            result.setNotes(e.getMessage());
            result.setOutputText("IOException");
            answer.releaseConnection();
            return result;
        }
        try {
            br = new BufferedReader(new InputStreamReader(answerStream, "iso-8859-2"));
        } catch (UnsupportedEncodingException e) {
        }
        String row = "";
        try {
            line = br.readLine();
            Pattern p2 = Pattern.compile("(<tr class=row0>)|(<tr class=stat_ac>)|(<tr class=stat_run>)");
            Matcher m2 = p2.matcher(line);
            while (!m2.find() && line != null) {
                line = br.readLine();
                m2 = p2.matcher(line);
            }
            row = "";
            for (int i = 0; i < 19; i++) {
                row += line;
                line = br.readLine();
            }
        } catch (IOException e) {
            result.setStatus(ResultsStatusEnum.UNDEF.getCode());
            result.setNotes(e.getMessage());
            result.setOutputText("IOException");
            sendAnswer.releaseConnection();
            return result;
        }
        String[] col = row.split("(<td>)|(</table>)");
        result.setPoints(0);
        if (col[6].matches(".*Program zaakceptowany.*")) {
            result.setStatus(ResultsStatusEnum.ACC.getCode());
            result.setPoints(input.getMaxPoints());
            result.setRuntime(10 * Integer.parseInt(col[8].replaceAll("\\.", "")));
            result.setMemUsed(Integer.parseInt(col[9].replaceAll("\\s", "")));
            break;
        } else if (col[6].matches(".*Bd kompilacji.*")) {
            result.setStatus(ResultsStatusEnum.CE.getCode());
            break;
        } else if (col[6].matches(".*Bd wykonania.*")) {
            result.setStatus(ResultsStatusEnum.RE.getCode());
            break;
        } else if (col[6].matches(".*Limit czasu przekroczony.*")) {
            result.setStatus(ResultsStatusEnum.TLE.getCode());
            break;
        } else if (col[6].matches(".*Limit pamici przekroczony.*")) {
            result.setStatus(ResultsStatusEnum.MLE.getCode());
            break;
        } else if (col[6].matches(".*Bdna odpowied.*")) {
            result.setStatus(ResultsStatusEnum.WA.getCode());
            break;
        } else if (col[6].matches(".*Niedozwolona funkcja.*")) {
            result.setStatus(ResultsStatusEnum.RV.getCode());
        } else if (col[6].matches(".*Uruchamianie.*")) {
        } else if (col[6].matches(".*Kompilacja.*")) {
        } else {
            result.setStatus(ResultsStatusEnum.UNKNOWN.getCode());
            result.setNotes("Unknown status: \"" + col[6] + "\"");
            break;
        }
        answer.releaseConnection();
    } while (true);
    GetMethod logout = new GetMethod("http://opss.assecobs.pl/?logoff");
    try {
        client.executeMethod(logout);
    } catch (HttpException e) {
        logout.releaseConnection();
    } catch (IOException e) {
        logout.releaseConnection();
    }
    logout.releaseConnection();
    return result;
}

From source file:pl.umk.mat.zawodyweb.compiler.classes.LanguageUVA.java

private void logIn(String login, String password) throws HttpException, IOException {
    ArrayList<NameValuePair> vectorLoginData;
    GetMethod get = new GetMethod(acmSite);

    try {/*from  w w w  .  j av a  2 s.c om*/
        client.executeMethod(get);
        InputStream firstGet = get.getResponseBodyAsStream();
        BufferedReader br = null;

        try {
            br = new BufferedReader(new InputStreamReader(firstGet, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
        }

        String line, name, value;
        vectorLoginData = new ArrayList<NameValuePair>();
        vectorLoginData.add(new NameValuePair("username", login));
        vectorLoginData.add(new NameValuePair("passwd", password));

        line = br.readLine();
        while (line != null && !line.matches(".*class=\"mod_login\".*")) {
            line = br.readLine();
        }
        while (line != null && !line.matches("(?i).*submit.*login.*")) {
            if (line.matches(".*hidden.*name=\".*value=\".*")) {
                name = line.split("name=\"")[1].split("\"")[0];
                value = line.split("value=\"")[1].split("\"")[0];
                vectorLoginData.add(new NameValuePair(name, value)); // FIXME: check if it's neccesary: URLDecoder.decode(value, "UTF-8"));
            }
            line = br.readLine();
        }
    } finally {

        get.releaseConnection();
    }
    vectorLoginData.add(new NameValuePair("remember", "yes"));
    vectorLoginData.add(new NameValuePair("Submit", "Login"));

    PostMethod post = new PostMethod(acmSite + "index.php?option=com_comprofiler&task=login");
    post.setRequestHeader("Referer", acmSite);
    NameValuePair[] loginData = new NameValuePair[0];
    loginData = vectorLoginData.toArray(loginData);
    post.setRequestBody(loginData);

    client.executeMethod(post);

    post.releaseConnection();
}

From source file:playground.jbischoff.carsharing.data.VBBRouteCatcher.java

private void run(Coord from, Coord to, long departureTime) {

    Locale locale = new Locale("en", "UK");
    String pattern = "###.000000";

    DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(locale);
    df.applyPattern(pattern);// www . j a v a 2 s .c  o  m

    // Construct data
    //X&Y coordinates must be exactly 8 digits, otherwise no proper result is given. They are swapped (x = long, y = lat)

    //Verbindungen 1-n bekommen; Laufweg, Reisezeit & Umstiege ermitteln
    String text = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>"
            + "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>"
            + "<ReqC accessId=\"JBischoff2486b558356fa9b81b1rzum\" ver=\"1.1\" requestId=\"7\" prod=\"SPA\" lang=\"DE\">"
            + "<ConReq>" + "<ReqT date=\"" + VBBDAY.format(departureTime) + "\" time=\""
            + VBBTIME.format(departureTime) + "\">" + "</ReqT>" + "<RFlags b=\"0\" f=\"1\" >" + "</RFlags>"
            + "<Start>" + "<Coord name=\"START\" x=\"" + df.format(from.getY()).replace(".", "") + "\" y=\""
            + df.format(from.getX()).replace(".", "") + "\" type=\"WGS84\"/>"
            + "<Prod  prod=\"1111000000000000\" direct=\"0\" sleeper=\"0\" couchette=\"0\" bike=\"0\"/>"
            + "</Start>" + "<Dest>" + "<Coord name=\"ZIEL\" x=\"" + df.format(to.getY()).replace(".", "")
            + "\" y=\"" + df.format(to.getX()).replace(".", "") + "\" type=\"WGS84\"/>" + "</Dest>"
            + "</ConReq>" + "</ReqC>";
    PostMethod post = new PostMethod("http://demo.hafas.de/bin/pub/vbb/extxml.exe/");
    post.setRequestBody(text);
    post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
    HttpClient httpclient = new HttpClient();
    try {

        int result = httpclient.executeMethod(post);

        // Display status code
        //                     System.out.println("Response status code: " + result);

        // Display response
        //                     System.out.println("Response body: ");
        //                     System.out.println(post.getResponseBodyAsString());

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(post.getResponseBodyAsStream());

        if (writeOutput) {
            BufferedWriter writer = IOUtils.getBufferedWriter(filename);
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            //initialize StreamResult with File object to save to file
            StreamResult res = new StreamResult(writer);
            DOMSource source = new DOMSource(document);
            transformer.transform(source, res);
            writer.flush();
            writer.close();

        }

        Node connectionList = document.getFirstChild().getFirstChild().getFirstChild();
        NodeList connections = connectionList.getChildNodes();
        int amount = connections.getLength();
        for (int i = 0; i < amount; i++) {
            Node connection = connections.item(i);
            Node overview = connection.getFirstChild();
            ;

            while (!overview.getNodeName().equals("Overview")) {
                overview = overview.getNextSibling();
            }

            System.out.println(overview.getChildNodes().item(3).getTextContent());
            int transfers = Integer.parseInt(overview.getChildNodes().item(3).getTextContent());
            String time = overview.getChildNodes().item(4).getFirstChild().getTextContent().substring(3);
            System.out.println(time);
            Date rideTime = VBBDATE.parse(time);
            int seconds = rideTime.getHours() * 3600 + rideTime.getMinutes() * 60 + rideTime.getSeconds();
            System.out.println(seconds + "s; transfers: " + transfers);
            if (seconds < this.bestRideTime) {
                this.bestRideTime = seconds;
                this.bestTransfers = transfers;
            }
        }
    } catch (Exception e) {
        this.bestRideTime = -1;
        this.bestTransfers = -1;
    }

    finally {
        // Release current connection to the connection pool 
        // once you are done
        post.releaseConnection();
        post.abort();

    }

}

From source file:smile.weixin.jdquanyi.tools.SendMsg_webchinese.java

/** 
 * @author dengsilinming //ww  w.  j a  va 2s.  c  o m
 * @date Sep 18, 2012 
 * @time 9:38:25 AM 
 * @param args 
 * @throws IOException 
 * @throws HttpException 
 * @description 
 */
public void send(String telephone, int id) throws HttpException, IOException {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod("http://gbk.sms.webchinese.cn");
    // PostMethod post = new PostMethod("http://sms.webchinese.cn/web_api/");  
    post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk");//   
    NameValuePair[] data = { new NameValuePair("Uid", "jdquanyi"), //   
            new NameValuePair("Key", "82594d54b061255b1d6d"), //   
            new NameValuePair("smsMob", telephone), //   
            new NameValuePair("smsText", "yzm " + id) };//   
    post.setRequestBody(data);

    client.executeMethod(post);
    Header[] headers = post.getResponseHeaders();
    int statusCode = post.getStatusCode();
    System.out.println("statusCode:" + statusCode);
    for (Header h : headers) {
        System.out.println("---" + h.toString());
    }
    String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
    System.out.println(result);
    post.releaseConnection();

}

From source file:socialtrade1.ChildThread.java

void FetchCookie() {

    try {/*from w  w  w  .j  av  a  2s.  c  o  m*/
        PostMethod Postmethod = new PostMethod(url);
        Postmethod.addRequestHeader("Host", "www.frenzzup.com");
        Postmethod.addRequestHeader("User-Agent",
                " Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36");
        Postmethod.addRequestHeader("Accept",
                "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,*/*;q=0.5");
        Postmethod.addRequestHeader("Accept-Language", "en-US,en;q=0.8");
        Postmethod.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch");
        Postmethod.addRequestHeader("X-Client-Data", "CKK2yQEIxLbJAQj9lcoB");
        Postmethod.addRequestHeader("Connection", "keepalive,Keep-Alive");
        Postmethod.addRequestHeader("Cookie", Cookie);
        Postmethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        Postmethod.setRequestBody(body);
        Postmethod.addRequestHeader("Content-Length", "" + body.length());
        Postmethod.getFollowRedirects();
        Postmethod.setFollowRedirects(true);
        HttpClient client = new HttpClient();
        int status = client.executeMethod(Postmethod);

        {
            Cookie[] cookies = client.getState().getCookies();
            int i = 0;
            String cookie = "";
            while (i < cookies.length) {
                cookie = cookie + ";" + cookies[i].getName() + "=" + cookies[i].getValue();
                i++;
            }

            cookie = cookie.trim();

            Utilities.ThreadCookie[PositionNumber] = cookie;

            if (cookie.charAt(0) == ';')
                cookie = cookie.substring(1);
            int n1 = cookie.indexOf("UserID=");
            int n2 = cookie.indexOf("&", n1);
            Utilities.userID[PositionNumber] = cookie.substring(n1 + 7, n2).trim();
            Engine.ThreadStatus[PositionNumber][state] = status;

            Utilities.ThreadResponse[PositionNumber][state] = Postmethod.getResponseBodyAsString();

        }
    } catch (Exception m) {
        System.out.println("status " + Engine.ThreadStatus[PositionNumber][state]);
        System.out.println(Cookie);
        m.printStackTrace();

    }
    ;
}

From source file:tools.devnull.jenkins.plugins.buildnotifications.PushoverMessage.java

@Override
public void send() {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod("https://api.pushover.net/1/messages.json");
    post.setRequestBody(new NameValuePair[] { new NameValuePair("token", appToken),
            new NameValuePair("user", userToken), new NameValuePair("message", content + "\n\n" + extraMessage),
            new NameValuePair("title", title), new NameValuePair("priority", priority.toString()),
            new NameValuePair("url", url), new NameValuePair("url_title", urlTitle) });
    try {/*from www . j a  v  a  2 s  .  c  o  m*/
        client.executeMethod(post);
    } catch (IOException e) {
        LOGGER.severe("Error while sending notification: " + e.getMessage());
        e.printStackTrace();
    }
}