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:org.apache.commons.rdf.impl.sparql.SparqlClient.java

List<Map<String, RdfTerm>> queryResultSet(final String query) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(endpoint);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("query", query));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    CloseableHttpResponse response2 = httpclient.execute(httpPost);

    try {//  ww  w .j  a  v a2  s.  c  o m
        HttpEntity entity2 = response2.getEntity();
        InputStream in = entity2.getContent();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser saxParser = spf.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        final SparqlsResultsHandler sparqlsResultsHandler = new SparqlsResultsHandler();
        xmlReader.setContentHandler(sparqlsResultsHandler);
        xmlReader.parse(new InputSource(in));
        /*
         for (int ch = in.read(); ch != -1; ch = in.read()) {
         System.out.print((char)ch);
         }
         */
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
        return sparqlsResultsHandler.getResults();
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException ex) {
        throw new RuntimeException(ex);
    } finally {
        response2.close();
    }

}

From source file:org.wso2.identity.integration.test.requestPathAuthenticator.RequestPathAuthenticatorInvalidUserTestCase.java

@Test(alwaysRun = true, description = "Request path authenticator login fail", dependsOnMethods = {
        "testLoginSuccess" })
public void testLoginFail() throws Exception {
    HttpPost request = new HttpPost(TRAVELOCITY_SAMPLE_APP_URL + "/samlsso?SAML2.HTTPBinding=HTTP-POST");
    List<NameValuePair> urlParameters = new ArrayList<>();
    urlParameters.add(new BasicNameValuePair("username", super.adminUsername));
    urlParameters.add(new BasicNameValuePair("password", "admin123"));
    request.setEntity(new UrlEncodedFormEntity(urlParameters));
    HttpResponse response = client.execute(request);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line;/* w  w  w .j av a 2 s .  c  o m*/
    String samlRequest = "";
    String secToken = "";

    while ((line = rd.readLine()) != null) {
        if (line.contains("name='SAMLRequest'")) {
            String[] tokens = line.split("'");
            samlRequest = tokens[5];
        }
        if (line.contains("name='sectoken'")) {
            String[] tokens = line.split("'");
            secToken = tokens[5];
        }
    }
    EntityUtils.consume(response.getEntity());
    request = new HttpPost(isURL + "samlsso");
    urlParameters = new ArrayList<>();
    urlParameters.add(new BasicNameValuePair("sectoken", secToken));
    urlParameters.add(new BasicNameValuePair("SAMLRequest", samlRequest));
    request.setEntity(new UrlEncodedFormEntity(urlParameters));
    HttpResponse response2 = client.execute(request);
    int responseCode = response2.getStatusLine().getStatusCode();
    Assert.assertEquals(responseCode, 302, "Login failure response returned code " + responseCode);
    Header location = response2.getFirstHeader("location");
    String SAMLResponse = location.getValue().split("&SAMLResponse=")[1].split("&")[0];
    SAMLResponse = decode(java.net.URLDecoder.decode(SAMLResponse, (DEFAULT_CHARSET)));
    Assert.assertTrue(SAMLResponse.contains("User authentication failed"),
            "SAML Response does not contained " + "error message at login failure.");
}

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

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

    try {//ww  w.  ja  v  a 2s .co  m
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair("method", "sample_userfields"));
        params.add(new BasicNameValuePair("username", _username));
        params.add(new BasicNameValuePair("password", _password));
        params.add(new BasicNameValuePair("id", _sampleId));

        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 ExportUserFieldsResponse(_export, handler.handleResponse(response),
                    status.getStatusCode(), job);
        else
            return new ExportUserFieldsResponse(_export, status.getReasonPhrase(), status.getStatusCode(), job);
    } catch (Exception e) {
        _export.getJob().error(
                "An error was encountered trying to get user defined fields for sample : " + _sampleId, e);
        return null;
    }
}

From source file:de.itomig.itoplib.GetItopJSON.java

/**
 * request data from itop server in json format
 * //from   w w  w  . j  a v a2s .  c o m
 * @param operation
 * @param itopClass
 * @param key
 * @param output_fields
 * @return
 */
public static String postJsonToItopServer(String operation, String itopClass, String key,
        String output_fields) {
    AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
    String result = "";

    try {
        HttpPost request = new HttpPost();
        String url = ItopConfig.getItopUrl();

        String req = url + "/webservices/rest.php?version=1.0";
        if (debug)
            Log.i(TAG, "req.=" + req);
        request.setURI(new URI(req));

        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(ItopConfig.getItopUserNameValuePair());
        postParameters.add(ItopConfig.getItopPwdNameValuePair());

        JSONObject jsd = new JSONObject();
        jsd.put("operation", operation);
        jsd.put("class", itopClass);
        jsd.put("key", key);
        jsd.put("output_fields", output_fields);

        postParameters.add(new BasicNameValuePair("json_data", jsd.toString()));
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
        request.setEntity(formEntity);

        // request.addHeader(HTTP.CONTENT_TYPE, "application/json");
        HttpResponse response = client.execute(request);
        String status = response.getStatusLine().toString();
        if (debug)
            Log.i(TAG, "status: " + status);

        if (status.contains("200") && status.contains("OK")) {

            // request worked fine, retrieved some data
            InputStream instream = response.getEntity().getContent();
            result = convertStreamToString(instream);
            Log.d(TAG, "result is: " + result);
        } else // some error in http response
        {
            Log.e(TAG, "Get data - http-ERROR: " + status);
            result = "ERROR: http status " + status;
        }

    } catch (Exception e) {
        // Toast does not work in background task
        Log.e(TAG, "Get data -  " + e.toString());
        result = "ERROR: " + e.toString();
    } finally {
        client.close(); // needs to be done for androidhttpclient
        if (debug)
            Log.i(TAG, "...finally.. get data finished");
    }
    return result;

}

From source file:com.antorofdev.util.Http.java

/**
 * Performs http POST petition to server.
 *
 * @param url        URL to perform POST petition.
 * @param parameters Parameters to include in petition.
 *
 * @return Response from the server./*www.java  2  s.  c  o  m*/
 * @throws IOException If the <tt>parameters</tt> have errors, connection timmed out,
 *                     socket timmed out or other error related with the connection occurs.
 */
public static HttpResponse post(String url, ArrayList<NameValuePair> parameters) throws IOException {
    HttpParams httpParameters = new BasicHttpParams();
    int timeoutConnection = 10000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    int timeoutSocket = 10000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpPost httppost = new HttpPost(url);

    if (parameters != null)
        httppost.setEntity(new UrlEncodedFormEntity(parameters));

    HttpResponse response = httpclient.execute(httppost);

    return response;
}

From source file:fedroot.dacs.http.DacsPostRequest.java

private HttpPost urlEncodedPost(WebServiceRequest webServiceRequest) {
    HttpPost urlEncodedPost = new HttpPost(webServiceRequest.getBaseURI());
    try {//from   w  w  w.  ja  va 2  s.  c o  m
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
                webServiceRequest.getNameValuePairs());
        // urlEncodedFormEntity = new UrlEncodedFormEntity(dacsWebServiceRequest.getNameValuePairs(), "UTF-8");
        urlEncodedPost.setEntity(urlEncodedFormEntity);
        return urlEncodedPost;
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(DacsPostRequest.class.getName()).log(Level.SEVERE, null, ex);
        throw new RuntimeException("Invalid DacsWebServiceRequest parameters " + ex.getMessage());
    }
}

From source file:com.parking.auth.LoginUserAsyncTask.java

protected Boolean doInBackground(String... tokens) {
    try {//from w  w  w.ja va  2  s. c o  m
        /** Don't follow redirects */
        http_client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);

        HttpPost httppost = new HttpPost(ParkingConstants.serverUrl + "/loginServlet");

        /** Add your data */
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("username", ParkingApplication.getAccount().name));
        nameValuePairs.add(new BasicNameValuePair("isDevice", "true"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response;
        response = http_client.execute(httppost);
        Log.v(TAG, "Respone is " + response.getStatusLine().getStatusCode());
        Log.v(TAG, response.getStatusLine().toString());

        if (response.getStatusLine().getStatusCode() == 200) {
            /** Extract JSON user message from user response */
            ObjectMapper objectMapper = new ObjectMapper();
            LicensePlateJsonObject licensePlate = objectMapper.readValue(response.getEntity().getContent(),
                    LicensePlateJsonObject.class);
            result = true;
            AppPreferences.getInstance()
                    .setLicensePlateString(licensePlate.getLicensePlateList().toUpperCase());
        }

    } catch (Exception e) {
        e.printStackTrace();
        result = false;
    } finally {
        http_client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    }
    return result;
}

From source file:guru.nidi.ramltester.loader.FormLoginUrlFetcher.java

@Override
public InputStream fetchFromUrl(CloseableHttpClient client, String base, String name) {
    try {/*from   ww  w  . j  a  va  2 s . com*/
        final HttpPost login = new HttpPost(base + "/" + loginUrl);
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair(loginField, this.login));
        params.add(new BasicNameValuePair(passwordField, password));
        postProcessLoginParameters(params);
        login.setEntity(new UrlEncodedFormEntity(params));
        final CloseableHttpResponse getResult = client.execute(postProcessLogin(login));
        if (getResult.getStatusLine().getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) {
            throw new RamlLoader.ResourceNotFoundException(name,
                    "Could not login: " + getResult.getStatusLine().toString());
        }
        EntityUtils.consume(getResult.getEntity());
        return super.fetchFromUrl(client, base + "/" + loadPath, name);
    } catch (IOException e) {
        throw new RamlLoader.ResourceNotFoundException(name, e);
    }
}

From source file:com.gmail.at.faint545.services.DataQueueService.java

@Override
protected void onHandleIntent(Intent intent) {
    String url = intent.getStringExtra("url");
    String api = intent.getStringExtra("api");
    StringBuilder results = new StringBuilder();

    HttpClient client = new DefaultHttpClient();
    HttpPost request = new HttpPost(url);

    ArrayList<NameValuePair> arguments = new ArrayList<NameValuePair>();
    arguments.add(new BasicNameValuePair(SabnzbdConstants.APIKEY, api));
    arguments.add(new BasicNameValuePair(SabnzbdConstants.OUTPUT, SabnzbdConstants.OUTPUT_JSON));
    arguments.add(new BasicNameValuePair(SabnzbdConstants.MODE, SabnzbdConstants.MODE_QUEUE));

    try {//from  w  w w  . j a  v a2  s .  com
        request.setEntity(new UrlEncodedFormEntity(arguments));
        HttpResponse result = client.execute(request);
        InputStream inStream = result.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(inStream), 8);
        String line;
        while ((line = br.readLine()) != null) {
            if (line.length() > 0) {
                results.append(line);
            }
        }
        br.close();
        inStream.close();

        Bundle extras = intent.getExtras();
        Messenger messenger = (Messenger) extras.get("messenger");
        Message message = Message.obtain();

        Bundle resultsBundle = new Bundle();
        resultsBundle.putString("results", results.toString());
        message.setData(resultsBundle);

        messenger.send(message);
        stopSelf();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}

From source file:com.abc.turkey.service.unfreeze.SmsService.java

private void login() {
    try {//  w ww.j ava 2 s  .c  o  m
        HttpPost httpPost = new HttpPost(loginUrl);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "yuzhibo468"));
        nvps.add(new BasicNameValuePair("password", "qq123654"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse response = httpclient.execute(httpPost);
        String res = EntityUtils.toString(response.getEntity(), "utf8");
        logger.debug(res);
        response.close();
    } catch (Exception e) {
        throw new ServiceException("Sms api login error!");
    }
}