Example usage for org.apache.commons.httpclient NameValuePair NameValuePair

List of usage examples for org.apache.commons.httpclient NameValuePair NameValuePair

Introduction

In this page you can find the example usage for org.apache.commons.httpclient NameValuePair NameValuePair.

Prototype

public NameValuePair(String name, String value) 

Source Link

Document

Constructor.

Usage

From source file:mitm.common.security.ca.handlers.comodo.CollectCustomClientCert.java

/**
 * Collects the certificate with the given orderNummer. 
 * @return true if successful, false if an error occurs
 * @throws CustomClientCertException//w  w  w.j a va  2  s  .  c om
 */
public boolean collectCertificate() throws CustomClientCertException {
    reset();

    if (StringUtils.isEmpty(loginName)) {
        throw new CustomClientCertException("loginName must be specified.");
    }

    if (StringUtils.isEmpty(loginPassword)) {
        throw new CustomClientCertException("loginPassword must be specified.");
    }

    if (StringUtils.isEmpty(orderNumber)) {
        throw new CustomClientCertException("orderNumber must be specified.");
    }

    PostMethod postMethod = new PostMethod(connectionSettings.getCollectCustomClientCertURL());

    NameValuePair[] data = { new NameValuePair("loginName", loginName),
            new NameValuePair("loginPassword", loginPassword), new NameValuePair("orderNumber", orderNumber),
            new NameValuePair("queryType", /* status and cert only */ "2"),
            new NameValuePair("responseType", /* Individually encoded */ "3"),
            new NameValuePair("responseEncoding", /* base64 */ "0") };

    postMethod.setRequestBody(data);

    HTTPMethodExecutor executor = new HTTPMethodExecutor(connectionSettings.getTotalTimeout(),
            connectionSettings.getProxyInjector());

    executor.setConnectTimeout(connectionSettings.getConnectTimeout());
    executor.setReadTimeout(connectionSettings.getReadTimeout());

    try {
        executor.executeMethod(postMethod, responseHandler);
    } catch (IOException e) {
        throw new CustomClientCertException(e);
    }

    return !error;
}

From source file:de.laeubisoft.tools.ant.validation.W3CCSSValidationTask.java

/**
 * Creates the actual request to the validation server for a given
 * {@link URL} and returns an inputstream the result can be read from
 * //from w  w  w .  j  a va2  s. com
 * @param uriToCheck
 *            the URL to check (or <code>null</code> if text or file should
 *            be used as input
 * @return the stream to read the response from
 * @throws IOException
 *             if unrecoverable communication error occurs
 * @throws BuildException
 *             if server returned unexspected results
 */
private InputStream buildConnection(final URL uriToCheck) throws IOException, BuildException {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("output", VALIDATOR_FORMAT_OUTPUT));
    if (uriToCheck != null) {
        params.add(new NameValuePair("uri", uriToCheck.toString()));
    } else {
        if (text != null) {
            params.add(new NameValuePair("text", text));
        }
    }
    if (usermedium != null) {
        params.add(new NameValuePair("usermedium", usermedium));
    }
    if (profile != null) {
        params.add(new NameValuePair("profile", profile));
    }
    if (lang != null) {
        params.add(new NameValuePair("lang", lang));
    }
    if (warning != null) {
        params.add(new NameValuePair("warning", warning));
    }
    HttpClient httpClient = new HttpClient();
    HttpMethodBase method;
    if (uriToCheck != null) {
        //URIs must be checked via traditonal GET...
        GetMethod getMethod = new GetMethod(validator);
        getMethod.setQueryString(params.toArray(new NameValuePair[0]));
        method = getMethod;
    } else {
        PostMethod postMethod = new PostMethod(validator);
        if (text != null) {
            //Text request must be multipart encoded too...
            postMethod.setRequestEntity(new MultipartRequestEntity(Tools.nvToParts(params).toArray(new Part[0]),
                    postMethod.getParams()));
        } else {
            //Finally files must be checked with multipart-forms....
            postMethod.setRequestEntity(
                    Tools.createFileUpload(file, "file", null, params, postMethod.getParams()));
        }
        method = postMethod;
    }
    int result = httpClient.executeMethod(method);
    if (result == HttpStatus.SC_OK) {
        return method.getResponseBodyAsStream();
    } else {
        throw new BuildException("Server returned " + result + " " + method.getStatusText());
    }

}

From source file:mesquite.tol.lib.BaseHttpRequestMaker.java

public static byte[] doPost(String url, Map additionalParameters) {
    PostMethod xmlPost = new PostMethod(url);
    NameValuePair[] argsArray = new NameValuePair[additionalParameters.keySet().size()];
    int i = 0;//from  w  w w.j a v  a 2s .  co m
    for (Iterator iter = additionalParameters.keySet().iterator(); iter.hasNext();) {
        String nextParamName = (String) iter.next();
        String nextValue = (String) additionalParameters.get(nextParamName);
        argsArray[i++] = new NameValuePair(nextParamName, nextValue);
    }
    xmlPost.setRequestBody(argsArray);
    return executePost(xmlPost);
}

From source file:com.bigcommerce.http.QueryStringBuilder.java

/**
 * Invokes {@link #addQueryParameter(NameValuePair)} with a <code>String</code>
 * converted value.// w ww .j  av a2s.  c o  m
 */
public QueryStringBuilder addQueryParameter(final String name, final float value) {
    return addQueryParameter(new NameValuePair(name, String.valueOf(value)));
}

From source file:edu.cmu.cs.diamond.pathfind.DjangoAnnotationStore.java

private void login(String loginuri) throws IOException {
    String username = prefs.get("username", "");
    String password = "";

    JLabel label = new JLabel("Please enter your username and password:");
    JTextField jtf = new JTextField(username);
    JPasswordField jpf = new JPasswordField();
    int dialogResult = JOptionPane.showConfirmDialog(null, new Object[] { label, jtf, jpf },
            "Login to PathFind", JOptionPane.OK_CANCEL_OPTION);
    if (dialogResult == JOptionPane.OK_OPTION) {
        username = jtf.getText();/*from w  ww. j  a va 2 s . co  m*/
        prefs.put("username", username);
        password = new String(jpf.getPassword());
    } else {
        throw new IOException("User refused to login");
    }

    // get the form to get the cookies
    GetMethod form = new GetMethod(loginuri);
    try {
        if (httpClient.executeMethod(form) != 200) {
            throw new IOException("Can't GET " + loginuri);
        }
    } finally {
        form.releaseConnection();
    }

    // get cookies
    Cookie[] cookies = httpClient.getState().getCookies();
    for (Cookie c : cookies) {
        System.out.println(c);
        if (c.getName().equals("csrftoken")) {
            csrftoken = c.getValue();
            break;
        }
    }

    // now, post
    PostMethod post = new PostMethod(loginuri);
    try {
        post.addRequestHeader("Referer", loginuri);
        NameValuePair params[] = { new NameValuePair("username", username),
                new NameValuePair("password", password), new NameValuePair("csrfmiddlewaretoken", csrftoken) };
        //System.out.println(Arrays.toString(params));
        post.setRequestBody(params);
        httpClient.executeMethod(post);
        System.out.println(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}

From source file:mitm.common.security.ca.handlers.comodo.Tier2PartnerDetails.java

/**
 * Requests a certificate. Returns true if a certificate was successfully requested.    
 *///  w ww .ja  va 2s.  co  m
public boolean retrieveDetails() throws CustomClientCertException {
    reset();

    if (StringUtils.isEmpty(loginName)) {
        throw new CustomClientCertException("loginName must be specified.");
    }

    if (StringUtils.isEmpty(loginPassword)) {
        throw new CustomClientCertException("loginPassword must be specified.");
    }

    PostMethod postMethod = new PostMethod(connectionSettings.getTier2PartnerDetailsURL());

    NameValuePair[] data = { new NameValuePair("loginName", loginName),
            new NameValuePair("loginPassword", loginPassword) };

    if (accountID != null) {
        data = (NameValuePair[]) ArrayUtils.add(data, new NameValuePair("accountID", accountID));
    }

    postMethod.setRequestBody(data);

    HTTPMethodExecutor executor = new HTTPMethodExecutor(connectionSettings.getTotalTimeout(),
            connectionSettings.getProxyInjector());

    executor.setConnectTimeout(connectionSettings.getConnectTimeout());
    executor.setReadTimeout(connectionSettings.getReadTimeout());

    try {
        executor.executeMethod(postMethod, responseHandler);
    } catch (IOException e) {
        throw new CustomClientCertException(e);
    }

    return !error;
}

From source file:com.rallydev.integration.build.rest.RallyRestService.java

public String findWorkspaceFlag(String workspaceName) throws IOException {
    NameValuePair wsParam, fetchParam;
    NameValuePair[] pairs;//from w  ww  . j a  v  a 2s.com
    String response, workspaceRef = null, workspaceOid = null;

    workspaceRef = findWorkspace(workspaceName);
    workspaceOid = extractId(workspaceRef);
    if (workspaceOid != null) {
        response = getObject("workspace", workspaceOid);
        if (response == null || !isValidResponse(response)) {
            return null;
        }
    } else {
        return null;
    }

    String reqUrl = getUrl() + "/workspaceconfiguration";
    GetMethod get = new GetMethod(reqUrl);
    wsParam = new NameValuePair("workspace", workspaceRef);
    fetchParam = new NameValuePair("fetch", "true");
    pairs = new NameValuePair[] { wsParam, fetchParam };

    get.setQueryString(pairs);
    response = doGet(new HttpClient(), get);
    if (response == null || !isValidResponse(response)) {
        return null;
    } else {
        return extractFlagFromResponse(response);
    }
}

From source file:com.github.maven.plugin.client.impl.GithubClientImpl.java

/**
 * Removes the given download from the repository download section.
 *
 * @param repositoryUrl The repository url.
 * @param artifactName The download name.
 *//*from   w ww.  j  a v  a2s . c  o  m*/
private void delete(String repositoryUrl, String artifactName) {
    final Map<String, Integer> downloads = retrieveDownloadsInfos(repositoryUrl);

    if (!downloads.containsKey(artifactName)) {
        throw new GithubArtifactNotFoundException(
                "The download " + artifactName + " cannot be found in " + repositoryUrl);
    }

    final String downloadUrl = String.format("%s/%d", toRepositoryDownloadUrl(repositoryUrl),
            downloads.get(artifactName));

    PostMethod githubDelete = new PostMethod(downloadUrl);
    githubDelete.setRequestBody(new NameValuePair[] { new NameValuePair("_method", "delete"),
            new NameValuePair("login", login), new NameValuePair("token", token) });

    try {
        int response = httpClient.executeMethod(githubDelete);
        if (response != HttpStatus.SC_MOVED_TEMPORARILY) {
            throw new GithubException("Unexpected error " + HttpStatus.getStatusText(response));
        }
    } catch (IOException e) {
        throw new GithubException(e);
    }

    githubDelete.releaseConnection();
}

From source file:com.momathink.common.tools.ToolMonitor.java

/**
 * HTTP POST?HTML//from   w ww. ja va  2  s.c  om
 *
 * @param url
 *            URL?
 * @param params
 *            ?,?null
 * @return ?HTML
 */
private String doPost(String url, Map<String, String> params) {
    StringBuffer result = new StringBuffer();
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    // Http Post?
    if (params != null) {
        NameValuePair[] data = new NameValuePair[params.size()];
        int i = 0;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            data[i++] = new NameValuePair(entry.getKey(), entry.getValue());
        }
        method.setRequestBody(data);
    }
    try {
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"));
            String str = null;
            while ((str = reader.readLine()) != null) {
                result.append(str);
            }
        }
    } catch (IOException e) {
    } finally {
        method.releaseConnection();
    }
    return result.toString();
}

From source file:com.bigcommerce.http.QueryStringBuilder.java

/**
 * Invokes {@link #addQueryParameter(NameValuePair)} with a <code>String</code>
 * converted value./*w  ww.  j a va 2 s . c o m*/
 */
public QueryStringBuilder addQueryParameter(final String name, final long value) {
    return addQueryParameter(new NameValuePair(name, String.valueOf(value)));
}