Example usage for org.apache.http.client.entity UrlEncodedFormEntity UrlEncodedFormEntity

List of usage examples for org.apache.http.client.entity UrlEncodedFormEntity UrlEncodedFormEntity

Introduction

In this page you can find the example usage for org.apache.http.client.entity UrlEncodedFormEntity UrlEncodedFormEntity.

Prototype

public UrlEncodedFormEntity(final Iterable<? extends NameValuePair> parameters) 

Source Link

Document

Constructs a new UrlEncodedFormEntity with the list of parameters with the default encoding of HTTP#DEFAULT_CONTENT_CHARSET

Usage

From source file:com.dianping.cosmos.monitor.HttpClientService.java

protected String excutePost(String url, List<NameValuePair> nvps) throws Exception {
    HttpClient httpClient = getHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    HttpResponse httpResponse = httpClient.execute(httpPost);
    String response = parseResponse(url, httpResponse);
    return response;
}

From source file:org.n52.oss.ui.controllers.RegisterController.java

@RequestMapping(value = "/user")
public String registerUser(@ModelAttribute(value = "username") String username,
        @ModelAttribute(value = "password") String password, ModelMap map, RedirectAttributes rs) {
    try {/*  ww w.  jav  a2s.c  o  m*/
        HttpPost post = new HttpPost(OSSConstants.BASE_URL + "/OpenSensorSearch/api/user/register");
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("username", username));
        pairs.add(new BasicNameValuePair("password", password));
        post.setEntity(new UrlEncodedFormEntity(pairs));

        HttpClient client = new DefaultHttpClient();
        HttpResponse resp = client.execute(post);
        StringBuilder result = new StringBuilder();
        String s = null;
        BufferedReader reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        while ((s = reader.readLine()) != null)
            result.append(s);

        status reg_result = new Gson().fromJson(result.toString(), status.class);
        if (reg_result.success) {
            map.put("RegisterSucceded", true);
            return "redirect:/";
        } else {
            String errorMsg = reg_result.reason == null ? "Cannot register currently" : reg_result.reason;
            map.put("RegisterFailed", true);
            map.put("ErrorMsg", errorMsg);
            return "register/index";
        }

    } catch (Exception e) {
        return null;
    }

}

From source file:edu.rit.csh.androidwebnews.HttpsPutAsyncTask.java

/**
 * The method that gets run when execute() is run. This sends the URL with the
 * PUT parameters to the server and gets the results
 *
 * @param params - [0] is the URL to got to, the rest are parameters to the request
 * @return String representation of page results
 *///from  w  w w.j  av a 2s  .  co m
@Override
protected String doInBackground(BasicNameValuePair... params) {
    ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
    String line;
    try {
        HttpPut request = new HttpPut(params[0].getValue());
        request.addHeader("accept", "application/json");
        //params = Arrays.copyOfRange(params, 1, params.length);

        for (BasicNameValuePair param : params) {
            nvp.add(new BasicNameValuePair(param.getName(), param.getValue()));
        }

        request.setEntity(new UrlEncodedFormEntity(nvp));

        HttpResponse response = httpclient.execute(request);
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuilder sb = new StringBuilder("");

        String NL = System.getProperty("line.separator");

        while ((line = in.readLine()) != null) {
            sb.append(line).append(NL);
        }
        in.close();
        return sb.toString();

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}

From source file:org.opencastproject.publication.youtube.remote.YouTubePublicationServiceRemoteImpl.java

@Override
public Job publish(MediaPackage mediaPackage, Track track) throws PublicationException {
    final String trackId = track.getIdentifier();
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("mediapackage", MediaPackageParser.getAsXml(mediaPackage)));
    params.add(new BasicNameValuePair("elementId", trackId));
    HttpPost post = new HttpPost();
    HttpResponse response = null;/*from   www.ja v  a2 s  . c o m*/
    try {
        post.setEntity(new UrlEncodedFormEntity(params));
        response = getResponse(post);
        if (response != null) {
            logger.info("Publishing {} to youtube", trackId);
            return JobParser.parseJob(response.getEntity().getContent());
        }
    } catch (Exception e) {
        throw new PublicationException("Unable to publish track " + trackId + " from mediapackage "
                + mediaPackage + " using a remote youtube publication service", e);
    } finally {
        closeConnection(response);
    }
    throw new PublicationException("Unable to publish track " + trackId + " from mediapackage " + mediaPackage
            + " using a remote youtube publication service");
}

From source file:org.labkey.freezerpro.export.ExportLocationCommand.java

public FreezerProCommandResonse execute(HttpClient client, PipelineJob job) {
    HttpPost post = new HttpPost(_url);

    try {/*from  w  ww.j  av a2s . c  o m*/
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair("method", "vials_sample"));
        params.add(new BasicNameValuePair("username", _username));
        params.add(new BasicNameValuePair("password", _password));
        params.add(new BasicNameValuePair("start", String.valueOf(_start)));
        params.add(new BasicNameValuePair("limit", String.valueOf(_limit)));

        post.setEntity(new UrlEncodedFormEntity(params));

        ResponseHandler<String> handler = new BasicResponseHandler();

        HttpResponse response = client.execute(post);
        StatusLine status = response.getStatusLine();

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            return new ExportLocationResponse(_export, handler.handleResponse(response), status.getStatusCode(),
                    job);
        else
            return new ExportLocationResponse(_export, status.getReasonPhrase(), status.getStatusCode(), job);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.skfiy.typhon.spi.auth.p.Four399Authenticator.java

@Override
public UserInfo authentic(OAuth2 oauth) {
    CloseableHttpClient hc = HC_BUILDER.build();
    HttpPost httpPost = new HttpPost("http://dev.sj.4399api.net/Rest?ac=checkToken");

    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair("uid", oauth.getUid()));
    nvps.add(new BasicNameValuePair("access_token", oauth.getCode()));
    nvps.add(new BasicNameValuePair("app_key", "100979"));
    nvps.add(new BasicNameValuePair("app_secret", "da7be84d18a8aec8a5a45bbc6e5889e9"));

    try {/*from  www  .  java  2s.  com*/

        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        JSONObject json = hc.execute(httpPost, new ResponseHandler<JSONObject>() {

            @Override
            public JSONObject handleResponse(HttpResponse response)
                    throws ClientProtocolException, IOException {
                String str = StreamUtils.copyToString(response.getEntity().getContent(),
                        StandardCharsets.UTF_8);
                return JSON.parseObject(str);
            }
        });

        if (json.getIntValue("code") != 10000) {
            throw new OAuth2Exception(json.getString("message"));
        }

        UserInfo info = new UserInfo();
        info.setUsername(getPlatform().getLabel() + "-" + json.getJSONObject("data").getString("username"));
        info.setPlatform(getPlatform());
        return info;
    } catch (IOException ex) {
        throw new OAuth2Exception("4399?", ex);
    } finally {
        try {
            hc.close();
        } catch (IOException ex) {
        }
    }
}

From source file:kindleclippings.quizlet.GetAccessToken.java

static JSONObject oauthDance() throws IOException, URISyntaxException, InterruptedException, JSONException {

    // start HTTP server, so when can get the authorization code
    InetSocketAddress addr = new InetSocketAddress(7777);
    HttpServer server = HttpServer.create(addr, 0);
    AuthCodeHandler handler = new AuthCodeHandler();
    server.createContext("/", handler);
    ExecutorService ex = Executors.newCachedThreadPool();
    server.setExecutor(ex);/*from  w w  w  . j  a  va  2 s .  c o m*/
    server.start();
    String authCode;
    try {
        Desktop.getDesktop()
                .browse(new URI(new StringBuilder("https://quizlet.com/authorize/")
                        .append("?scope=read%20write_set").append("&client_id=" + clientId)
                        .append("&response_type=code").append("&state=" + handler.state).toString()));

        authCode = handler.result.take();
    } finally {
        server.stop(0);
        ex.shutdownNow();
    }

    if (authCode == null || authCode.length() == 0)
        return null;

    HttpPost post = new HttpPost("https://api.quizlet.com/oauth/token");
    post.setHeader("Authorization", authHeader);

    post.setEntity(
            new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("grant_type", "authorization_code"),
                    new BasicNameValuePair("code", authCode))));
    HttpResponse response = new DefaultHttpClient().execute(post);

    ByteArrayOutputStream buffer = new ByteArrayOutputStream(1000);
    response.getEntity().writeTo(buffer);
    return new JSONObject(new String(buffer.toByteArray(), "UTF-8"));
}

From source file:at.ac.tuwien.dsg.esperstreamprocessing.utils.RestHttpClient.java

public void callPostMethod(List<NameValuePair> paramList) {

    try {/*from  ww w  .  jav  a 2  s .  c o m*/

        HttpPost post = new HttpPost(url);

        // add header
        //  post.setHeader("Host", "smartsoc.infosys.tuwien.ac.at");
        //post.setHeader("User-Agent", USER_AGENT);
        //post.setHeader("Connection", "keep-alive");
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");

        // set content
        post.setEntity(new UrlEncodedFormEntity(paramList));
        //    Logger.getLogger(EventHandler.class.getName()).log(Level.INFO, "\nSending 'POST' request to URL : " + url);
        //   Logger.getLogger(EventHandler.class.getName()).log(Level.INFO, "Configuring..");

        //   Logger.getLogger(EventHandler.class.getName()).log(Level.INFO, "Post parameters : " + paramList);

        HttpClient client = HttpClientBuilder.create().build();
        HttpResponse response = client.execute(post);

        int responseCode = response.getStatusLine().getStatusCode();

        Logger.getLogger(RestHttpClient.class.getName()).log(Level.INFO, "Connection : " + url);
        Logger.getLogger(RestHttpClient.class.getName()).log(Level.INFO, "Response Code : " + responseCode);

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        //  Logger.getLogger(EventHandler.class.getName()).log(Level.INFO, result.toString());

    } catch (Exception ex) {

    }

}

From source file:com.appdirect.sdk.feature.OrderValidationIsWiredUpIntegrationTest.java

@Test
public void testValidationEdnpoint_whenPostSent_DefaultHandlerRespondsWith200() throws Exception {
    //Given/*from w  w  w . jav a 2 s  .c o m*/
    HttpPost httpPost = new HttpPost(
            format("http://localhost:%d/unsecured/integration/orderValidation", localConnectorPort));
    List<NameValuePair> keys = new ArrayList<>();
    keys.add(new BasicNameValuePair("aKey", "aValue"));
    httpPost.setEntity(new UrlEncodedFormEntity(keys));

    //When
    HttpResponse response = httpClient.execute(httpPost);

    //Then
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
}

From source file:org.apache.camel.component.restlet.RestletPostFormTest.java

@Test
public void testPostBody() throws Exception {
    HttpUriRequest method = new HttpPost("http://localhost:" + portNum + "/users");

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("foo", "bar"));

    ((HttpEntityEnclosingRequestBase) method).setEntity(new UrlEncodedFormEntity(urlParameters));

    HttpResponse response = doExecute(method);

    assertHttpResponse(response, 200, "text/plain");
}