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, final Charset charset) 

Source Link

Document

Constructs a new UrlEncodedFormEntity with the list of parameters in the specified encoding.

Usage

From source file:hu.sztaki.lpds.portal.util.stream.HttpClient.java

/**
 * Getting the stream/*from   w w w.  j a  va 2  s  . c  o  m*/
 * @param pValue list of the parameters used during the connection
 * @return  datastream
 * @throws java.io.IOException communication error
 */
public InputStream getStream(Hashtable<String, String> pValue) throws IOException {
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    Enumeration<String> enm = pValue.keys();
    String key;
    while (enm.hasMoreElements()) {
        key = enm.nextElement();
        nvps.add(new BasicNameValuePair(key, pValue.get(key)));
    }
    httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    HttpResponse response = httpclient.execute(httpPost);
    HttpEntity entity = response.getEntity();
    return entity.getContent();
}

From source file:org.keycloak.testsuite.util.DeleteMeOAuthClient.java

public AccessTokenResponse getToken(String realm, String clientId, String clientSecret, String username,
        String password) {/*from w w w .j  a va  2  s.  c  o m*/
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost post = new HttpPost(
                OIDCLoginProtocolService.tokenUrl(UriBuilder.fromUri(baseUrl)).build(realm));

        List<NameValuePair> parameters = new LinkedList<NameValuePair>();
        parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD));
        parameters.add(new BasicNameValuePair("username", username));
        parameters.add(new BasicNameValuePair("password", password));
        if (clientSecret != null) {
            String authorization = BasicAuthHelper.createHeader(clientId, clientSecret);
            post.setHeader("Authorization", authorization);
        } else {
            parameters.add(new BasicNameValuePair("client_id", clientId));
        }

        UrlEncodedFormEntity formEntity;
        try {
            formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        post.setEntity(formEntity);

        CloseableHttpResponse response = httpclient.execute(post);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed to retrieve token: " + response.getStatusLine().toString()
                    + " / " + IOUtils.toString(response.getEntity().getContent()));
        }

        return JsonSerialization.readValue(response.getEntity().getContent(), AccessTokenResponse.class);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:lv.vizzual.numuri.service.http.HttpProvider.java

private void processPost(Request req) throws IOException {
    HttpPost post = null;//from   w  w  w  .ja  va2  s.  co m
    String result = null;
    HttpResponse response = null;

    try {
        post = new HttpPost(new URI(req.getUrl()));
        for (NameValuePair nv : req.getHeaders()) {
            post.setHeader(nv.getName(), nv.getValue());
        }

        post.setEntity(new UrlEncodedFormEntity(req.getData(), HTTP.UTF_8));
        response = client.execute(post);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            result = convertStreamToString(is);

            req.setResult(result);
            req.setSuccess(true);
        }
    } catch (IOException ex) {
        Log.d(TAG, "request failed", ex);
        req.setSuccess(false);
    } catch (URISyntaxException ex) {
        Log.d(TAG, "uri invalid", ex);
        req.setSuccess(false);
    }
}

From source file:com.unifonic.sdk.HttpSender.java

public OTSRestResponse request(String url, List<NameValuePair> data) throws IOException {
    log.debug("URL:" + url);
    log.debug("DATA:" + data);
    return requestDefault(url, new UrlEncodedFormEntity(data, HTTP.UTF_8));
    //return requestDefault(url, new UrlEncodedFormEntity(data));
}

From source file:wordGame.Util.WebUtil.java

public static boolean SaveBoardToServer(Board board, String userID, String cubesID, String dictID)
        throws UnsupportedEncodingException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost postMethod = new HttpPost(WEBCREATEBOARD);
    String boardData = board.toWebString();
    List<NameValuePair> formParameters = new ArrayList<NameValuePair>();
    formParameters.add(new BasicNameValuePair("board_data", boardData));
    formParameters.add(new BasicNameValuePair("user_id", userID));
    formParameters.add(new BasicNameValuePair("cubes_id", cubesID));
    formParameters.add(new BasicNameValuePair("dictionary_id", dictID));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParameters, "UTF-8");
    postMethod.setEntity(entity);/*  w w w  .  j  av a  2 s. c  om*/
    try {
        HttpResponse response = httpclient.execute(postMethod);
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            responseEntity.writeTo(System.out);
        }

        return true;
    } catch (IOException e) {
        return false;
    }

}

From source file:com.phodev.http.tools.RequestEntity.java

public RequestEntity setPostEntitiy(List<NameValuePair> postValues, String charset) {
    try {/*from w  w  w.  java2 s  . c o m*/
        postEntity = new UrlEncodedFormEntity(postValues, charset);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return this;
}

From source file:hu.balazsbakai.sq.util.RestUtil.java

public void executePOST() throws Exception {
    HttpPost request = new HttpPost(url);

    for (NameValuePair h : headers) {
        request.addHeader(h.getName(), h.getValue());
    }/*from ww w  .  j a  v  a  2 s.c o m*/

    if (!parameters.isEmpty()) {
        request.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8));
    }

    executeRequest(request, url);
}

From source file:com.halzhang.android.apps.startupnews.snkit.SNApi.java

/**
 * /*  w w w  .  ja  v a2  s. co  m*/
 * 
 * @param fnid
 * @param text
 * @param responseHandler
 */
public void comment(Context context, String fnid, String text, AsyncHttpResponseHandler responseHandler) {
    ArrayList<NameValuePair> valuePairs = new ArrayList<NameValuePair>(2);
    valuePairs.add(new BasicNameValuePair("fnid", fnid));
    valuePairs.add(new BasicNameValuePair("text", text));
    try {
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, HTTP.UTF_8);
        mAsyncHttpClient.post(context, context.getString(R.string.host, "/r"), entity,
                "application/x-www-form-urlencoded", responseHandler);
    } catch (UnsupportedEncodingException e) {
        CDLog.e(LOG_TAG, e.getMessage());
    }
}

From source file:org.opencastproject.silencedetection.remote.SilenceDetectionServiceRemote.java

@Override
public Job detect(Track sourceTrack, Track[] referencedTracks) throws SilenceDetectionFailedException {
    HttpPost post = new HttpPost("/detect");
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    try {/*from www.j av a  2s.c o m*/
        params.add(new BasicNameValuePair("track", MediaPackageElementParser.getAsXml(sourceTrack)));
        if (referencedTracks != null && referencedTracks.length > 0) {
            String referencedTracksXml = MediaPackageElementParser
                    .getArrayAsXml(Arrays.asList(referencedTracks));
            params.add(new BasicNameValuePair("referenceTracks", referencedTracksXml));
        }
        post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    } catch (Exception e) {
        throw new SilenceDetectionFailedException(
                "Unable to assemble a remote silence detection request for track "
                        + sourceTrack.getIdentifier());
    }

    HttpResponse response = null;
    try {
        response = getResponse(post);
        if (response != null) {
            String entity = EntityUtils.toString(response.getEntity());
            if (StringUtils.isNotEmpty(entity)) {
                Job resultJob = JobParser.parseJob(entity);
                logger.info("Start silence detection for track '{}' on remote silence detection service",
                        sourceTrack.getIdentifier());
                return resultJob;
            }
        }
    } catch (Exception e) {
        throw new SilenceDetectionFailedException("Unable to run silence detection for track "
                + sourceTrack.getIdentifier() + " on remote silence detection service", e);
    } finally {
        closeConnection(response);
    }
    throw new SilenceDetectionFailedException("Unable to run silence detection for track "
            + sourceTrack.getIdentifier() + " on remote silence detection service");
}

From source file:org.niceday.AsyncHttpPost.java

@Override
public void run() {
    try {/*www .j a v a 2 s.  co m*/
        request = new HttpPost(url);
        Log.d(AsyncHttpPost.class.getName(), "AsyncHttpGet  request to url :" + url);
        request.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);
        request.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout);
        if (parameter != null && parameter.size() > 0) {
            List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
            for (RequestParameter p : parameter) {
                list.add(new BasicNameValuePair(p.getName(), p.getValue()));
            }
            ((HttpPost) request).setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
        }
        HttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            ByteArrayOutputStream content = new ByteArrayOutputStream();
            response.getEntity().writeTo(content);
            String ret = new String(content.toByteArray()).trim();
            content.close();
            Object Object = null;
            if (AsyncHttpPost.this.handler != null) {
                Object = AsyncHttpPost.this.handler.handle(ret);
                if (AsyncHttpPost.this.requestCallback != null && Object != null) {
                    AsyncHttpPost.this.requestCallback.onSuccess(Object);
                    return;
                }
                if (Object == null || "".equals(Object.toString())) {
                    RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                            "");
                    AsyncHttpPost.this.requestCallback.onFail(exception);
                }
            } else {
                AsyncHttpPost.this.requestCallback.onSuccess(ret);
            }
        } else {
            RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                    "," + statusCode);
            AsyncHttpPost.this.requestCallback.onFail(exception);
        }

        Log.d(AsyncHttpPost.class.getName(), "AsyncHttpGet  request to url :" + url + "  finished !");
    } catch (java.lang.IllegalArgumentException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        Log.d(AsyncHttpGet.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (org.apache.http.conn.ConnectTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        Log.d(AsyncHttpPost.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (java.net.SocketTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        Log.d(AsyncHttpPost.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        RequestException exception = new RequestException(RequestException.UNSUPPORTED_ENCODEING_EXCEPTION,
                "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        Log.d(AsyncHttpPost.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  UnsupportedEncodingException  " + e.getMessage());
    } catch (org.apache.http.conn.HttpHostConnectException e) {
        RequestException exception = new RequestException(RequestException.CONNECT_EXCEPTION, "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        Log.d(AsyncHttpPost.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  HttpHostConnectException  " + e.getMessage());
    } catch (ClientProtocolException e) {
        RequestException exception = new RequestException(RequestException.CLIENT_PROTOL_EXCEPTION,
                "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        e.printStackTrace();
        Log.d(AsyncHttpPost.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  ClientProtocolException " + e.getMessage());
    } catch (IOException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        e.printStackTrace();
        Log.d(AsyncHttpPost.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  IOException  " + e.getMessage());
    } finally {
        //request.
    }
    super.run();
}