Example usage for org.apache.http.message BasicNameValuePair BasicNameValuePair

List of usage examples for org.apache.http.message BasicNameValuePair BasicNameValuePair

Introduction

In this page you can find the example usage for org.apache.http.message BasicNameValuePair BasicNameValuePair.

Prototype

public BasicNameValuePair(String str, String str2) 

Source Link

Usage

From source file:es.upm.oeg.examples.watson.service.MachineTranslationService.java

public String translate(String text, String sid) throws IOException, URISyntaxException {

    logger.info("Text to translate :" + text);
    logger.info("Translation type :" + sid);

    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("txt", text));
    qparams.add(new BasicNameValuePair("sid", sid));
    qparams.add(new BasicNameValuePair("rt", "text"));

    Executor executor = Executor.newInstance();
    URI serviceURI = new URI(baseURL).normalize();
    String auth = username + ":" + password;
    byte[] responseB = executor.execute(Request.Post(serviceURI)
            .addHeader("Authorization", "Basic " + Base64.encodeBase64String(auth.getBytes()))
            .bodyString(URLEncodedUtils.format(qparams, "utf-8"), ContentType.APPLICATION_FORM_URLENCODED))
            .returnContent().asBytes();/*from   w  w  w .  ja  v a  2 s  . c o  m*/

    String response = new String(responseB, "UTF-8");

    logger.info("Translation response :" + response);

    return response;

}

From source file:com.clxcommunications.xms.InboundsFilterTest.java

@Test
public void canGenerateQueryParameters() throws Exception {
    InboundsFilter filter = ClxApi.inboundsFilter().pageSize(20).addRecipient("12345", "9876")
            .startDate(LocalDate.of(2010, 11, 12)).endDate(LocalDate.of(2011, 11, 12)).build();

    List<NameValuePair> actual = filter.toQueryParams(4);

    assertThat(actual,/*w w w.j  a  v  a  2s.c om*/
            containsInAnyOrder((NameValuePair) new BasicNameValuePair("page", "4"),
                    new BasicNameValuePair("to", "12345,9876"), new BasicNameValuePair("page_size", "20"),
                    new BasicNameValuePair("start_date", "2010-11-12"),
                    new BasicNameValuePair("end_date", "2011-11-12")));
}

From source file:autopostsoicomputer.API.WPApi.java

@Override
public void createNewPostWP(PostObject po, String strUrlWordpress)
        throws UnsupportedEncodingException, IOException {
    strUrlWordpress += "createpost.php";
    for (;;) {/*from  w  w  w.j  a v a 2  s . c om*/
        try {
            HttpClient client = new DefaultHttpClient();

            ////// Get Variable
            String strPostTitle = po.getPostTitle();
            // check if postTitle has posted

            String strPostImageFeature = po.getPostImageFeature();
            String strPostCategory = po.getPostCategory();
            String strPostContent = po.getPostContent();
            //////
            HttpPost post = new HttpPost(strUrlWordpress);

            // add header
            post.setHeader("User-Agent", "PosterBotDefault");

            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
            urlParameters.add(new BasicNameValuePair("user", USER));
            urlParameters.add(new BasicNameValuePair("pass", PASS));
            urlParameters.add(new BasicNameValuePair("post_title", strPostTitle));
            urlParameters.add(new BasicNameValuePair("cat", strPostCategory));
            urlParameters.add(new BasicNameValuePair("post_content", strPostContent));
            urlParameters.add(new BasicNameValuePair("image_future", strPostImageFeature));

            post.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));
            HttpResponse response = client.execute(post);
            System.out.println("\nSending 'POST' request to URL : " + strUrlWordpress);
            System.out.println("Post parameters : " + post.getEntity());
            System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

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

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

            System.out.println(result.toString());
            if (response.getStatusLine().getStatusCode() == 200) {
                ReaderFactory.getInstance().writeFile(strPostTitle);
            }
        } catch (Exception ex) {
            System.out.println("ERROR CREATE POST : " + ex.toString());
            count_getPost++;
            if (count_getPost == maxTries_getPost) {
                System.out.println("I TRY CREATE POST TO!!! " + strUrlWordpress);
                count_getPost = 0;
                break;
            } else {
                System.out.println("TRY TIMES  : " + count_getPost);
                createNewPostWP(po, strUrlWordpress);
            }
        } finally {
            break;
        }
    }
}

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

@Override
public InputStream fetchFromUrl(CloseableHttpClient client, String base, String name, long ifModifiedSince) {
    try {/* w w w  . j  a  v a  2 s .c o m*/
        final HttpPost login = new HttpPost(base + "/" + loginUrl);
        final 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));
        try (final CloseableHttpResponse getResult = client.execute(postProcessLogin(login))) {
            if (getResult.getStatusLine().getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) {
                throw new Loader.ResourceNotFoundException(name,
                        "Could not login: " + getResult.getStatusLine().toString());
            }
            EntityUtils.consume(getResult.getEntity());
        }
        return super.fetchFromUrl(client, base + "/" + loadPath, name, ifModifiedSince);
    } catch (IOException e) {
        throw new Loader.ResourceNotFoundException(name, e);
    }
}

From source file:lh.api.showcase.server.api.lh.referencedata.ReferenceDataServiceImpl.java

@Override
public String getCountries(CountryCode countryCode, LanguageCode lang) throws HttpErrorResponseException {

    ReferenceDataRequestFactoryImpl reqFact = new ReferenceDataRequestFactoryImpl();
    try {/*from w w w .  jav  a  2s  . co  m*/
        URI uri = reqFact.getRequestUri(
                (NameValuePair) new BasicNameValuePair("countries",
                        (countryCode == null) ? ("") : (countryCode.toString())),
                null, Arrays.asList((NameValuePair) new BasicNameValuePair("lang",
                        (lang == null) ? ("") : (lang.toString()))));

        return HttpQueryUtils.executeQuery(uri);

    } catch (URISyntaxException e) {
        logger.log(Level.SEVERE, e.getMessage());
    }
    return null;
}

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

private void login() {
    try {// w  w  w .  ja v  a 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!");
    }
}

From source file:fr.eurecom.nerd.client.Request2.java

protected static synchronized String request(String uri, RequestType method,
        MultivaluedMap<String, String> queryParams) {
    HttpClient client = new DefaultHttpClient();

    //        System.out.println("TIMEOUTS= "+client.getProperties().get(ClientConfig.PROPERTY_READ_TIMEOUT)+"    "+client.getProperties().get(ClientConfig.PROPERTY_READ_TIMEOUT));
    //        client.setReadTimeout(timeout);
    //        client.setConnectTimeout(timeout);
    ///*  ww w.  ja v a2s .c om*/
    //        System.out.println("TIMEOUTS= "+client.getProperties().get(ClientConfig.PROPERTY_READ_TIMEOUT)+"    "+client.getProperties().get(ClientConfig.PROPERTY_READ_TIMEOUT));

    //WebResource webResource = client.resource(uri);

    String json = null;

    List<NameValuePair> nameValuePairs = new LinkedList<NameValuePair>();
    Iterator<String> paramsIterator = queryParams.keySet().iterator();

    switch (method) {
    case GET:

        while (paramsIterator.hasNext()) {
            String param = paramsIterator.next();
            List<String> listValues = queryParams.get(param);
            String value = "";
            for (int v = 0; v < listValues.size(); v++) {
                value = value + listValues.get(v);
                if (v + 1 != listValues.size())
                    value = value + ",";
            }
            BasicNameValuePair pair = new BasicNameValuePair(param, value);
            nameValuePairs.add(pair);
        }

        String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8");

        uri = uri + paramString;
        HttpGet get = new HttpGet(uri);

        try {
            HttpResponse response = client.execute(get);

            json = IOUtils.toString(response.getEntity().getContent(), "UTF-8");

        } catch (IOException e) {
            e.printStackTrace();
        }

        /*            json = webResource.
                queryParams(queryParams).
                accept(MediaType.APPLICATION_JSON_TYPE).
                get(String.class);*/
        break;

    case POST:

        HttpPost post = new HttpPost(uri);
        try {

            while (paramsIterator.hasNext()) {
                String param = paramsIterator.next();
                List<String> listValues = queryParams.get(param);
                String value = "";
                for (int v = 0; v < listValues.size(); v++) {
                    value = value + listValues.get(v);
                    if (v + 1 != listValues.size())
                        value = value + ",";
                }
                BasicNameValuePair pair = new BasicNameValuePair(param, value);
                nameValuePairs.add(pair);
            }

            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = client.execute(post);

            json = IOUtils.toString(response.getEntity().getContent(), "UTF-8");

        } catch (IOException e) {
            e.printStackTrace();
        }

        /*            
                    json = webResource.
                accept(MediaType.APPLICATION_JSON_TYPE). 
                post(String.class, queryParams);
                    break;*/

    default:
        break;
    }

    return json;
}

From source file:me.carpela.network.pt.cracker.http.impl.BasicHttpAgent.java

@Override
public boolean sendPacket(String url, TrackerRequestParameter param) {
    if (!checkTRP(param)) {
        logger.error("Packet not sent: request parameter illegal!");
        return false;
    }/* ww w.  j  a  v a2  s.  co m*/

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("uploaded", "" + param.getUploaded()));
    params.add(new BasicNameValuePair("downloaded", "" + param.getDownloaded()));
    params.add(new BasicNameValuePair("left", "" + param.getLeft()));

    params.add(new BasicNameValuePair("peer_id", Config.peer_id));
    params.add(new BasicNameValuePair("port", "" + Config.port));
    if (StringUtils.isNotBlank(param.getEvent())) {
        params.add(new BasicNameValuePair("event", param.getEvent()));
    }

    String result = sendGet(url, params);

    logger.info("Packet sent, with reponse: " + result);
    return true;
}

From source file:testclientside.implement.implPerson.java

@Override
public void save(Person p) {
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<>(3);
    nameValuePairs.add(new BasicNameValuePair("id", p.getId()));
    nameValuePairs.add(new BasicNameValuePair("nama", p.getNama()));
    nameValuePairs.add(new BasicNameValuePair("hobi", p.getHobi()));
    Service.ServicePost("insert.php", nameValuePairs);
}

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

/**
 * request data from itop server in json format
 * /*from   w ww .ja v  a 2  s .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;

}