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:ro.razius.vianet.LoginTask.java

@Override
protected Void doInBackground(String... params) {
    // set the connection and socket timeouts
    HttpParams httpParameters = new BasicHttpParams();
    int timeoutConnection = 3000;
    int timeoutSocket = 5000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    // build out GET URL
    List<NameValuePair> postParams = new LinkedList<NameValuePair>();
    postParams.add(new BasicNameValuePair(userParam, params[0]));
    postParams.add(new BasicNameValuePair(passParam, params[1]));

    HttpPost httppost = new HttpPost(authURL);

    // finally do the GET request to login to the ISA Server
    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    try {//from www.  j  av  a2 s  . c  om
        Log.d(TAG, "Trying to auth with: " + authURL);
        httppost.setEntity(new UrlEncodedFormEntity(postParams));
        HttpResponse response = httpClient.execute(httppost);
        Log.d(TAG, "HTTP Response: " + response.getStatusLine().toString());
    } catch (Exception e) {
        Log.d(TAG, e.toString()); // no use for errors
    }
    return null;
}

From source file:com.ChiriChat.DataAccessObject.DAOWebServer.ChiriChatMensajesDAO.java

@Override
public Mensajes insert(Mensajes dto) throws Exception {

    //Enviamos una peticion post al insert del usuario.
    HttpPost httpPostNewMensaje = new HttpPost("http://chirichatserver.noip.me:85/ws/newMensaje");

    //Creo el objeto Jason con los datos del contacto que se registra en la app.
    JSONObject newUsuario = new JSONObject();
    try {//from w  ww  . j  av  a2 s.c  om
        newUsuario.put("idConver", dto.getIdConversacion());
        newUsuario.put("idUsuario", dto.getIdUsuario());
        newUsuario.put("texto", dto.getCadena());
    } catch (JSONException e) {
        e.printStackTrace();
    }

    List parametros = new ArrayList();
    //Aade a la peticion post el parametro json, que contiene los datos a insertar.(json)
    parametros.add(new BasicNameValuePair("json", newUsuario.toString()));

    //Creamos la entidad con los datos que le hemos pasado
    httpPostNewMensaje.setEntity(new UrlEncodedFormEntity(parametros));

    //Objeto para poder obtener respuesta del server
    HttpResponse response = httpClient.execute(httpPostNewMensaje);
    //Obtenemos el codigo de la respuesta
    int respuesta = response.getStatusLine().getStatusCode();
    Log.w("Respueta", "" + respuesta);
    //Si respuesta 200 devuelvo mi usuario , si no devolvere null
    if (respuesta == 200) {

        //Nos conectamos para recibir los datos de respuesta
        HttpEntity entity = response.getEntity();
        //Creamos el InputStream
        InputStream is = entity.getContent();
        //Leemos el inputStream
        String temp = StreamToString(is);
        //Creamos el JSON con la cadena del inputStream
        Log.d("Cadena JSON", temp.toString());
        JSONObject jsonRecibido = new JSONObject(temp);

        Log.d("InputStreamReader", temp.toString());
        Log.d("JSON ==>", jsonRecibido.toString());

        Mensajes mensaje = new Mensajes(jsonRecibido);

        return mensaje;
    }

    return null;
}

From source file:org.springframework.social.reddit.connect.RedditOAuth2Template.java

private String getAccessToken(String code, String redirectUrl)
        throws UnsupportedEncodingException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//from   w w w  . j  a v  a  2  s  .c o m

        //Reddit Requires clientId and clientSecret be attached via basic auth
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("ssl.reddit.com", 443),
                new UsernamePasswordCredentials(clientId, clientSecret));

        HttpPost httppost = new HttpPost(RedditPaths.OAUTH_TOKEN_URL);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>(3);
        nvps.add(new BasicNameValuePair("code", code));
        nvps.add(new BasicNameValuePair("grant_type", "authorization_code"));
        nvps.add(new BasicNameValuePair("redirect_uri", redirectUrl));

        httppost.setEntity(new UrlEncodedFormEntity(nvps));
        httppost.addHeader("User-Agent", "a unique user agent");
        httppost.setHeader("Accept", "any;");

        HttpResponse request = httpclient.execute(httppost);
        HttpEntity response = request.getEntity(); // Reddit response containing accessToken

        if (response != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader(response.getContent()));
            StringBuilder content = new StringBuilder();
            String line;
            while (null != (line = br.readLine())) {
                content.append(line);
            }
            System.out.println(content.toString());
            Map json = (Map) JSONValue.parse(content.toString());
            if (json.containsKey("access_token")) {
                return (String) (json.get("access_token"));
            }
        }
        EntityUtils.consume(response);
    } finally {
        httpclient.getConnectionManager().shutdown(); //cleanup
    }
    return null;
}

From source file:se.kodapan.io.http.wayback.TestWayback.java

@Test
public void testPOST() throws Exception {

    Wayback wayback = new Wayback();
    wayback.setPath(new File("target/tmp/" + System.currentTimeMillis()));
    wayback.open();//from ww w  . j a  v  a 2  s.c  om

    long now = System.currentTimeMillis();

    HttpPost post = new HttpPost();
    post.setURI(new URI("http://www.jsonlint.com/ajax/validate"));

    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("json", "{ foo : 'bar' }"));
    pairs.add(new BasicNameValuePair("reformat", "yes"));
    UrlEncodedFormEntity form = new UrlEncodedFormEntity(pairs);
    post.setEntity(form);

    HttpResponse response1 = wayback.execute(post, now);
    HttpResponse response2 = wayback.execute(post, now);

    //    assertEquals(response1, response2);

    now = System.currentTimeMillis();

    HttpResponse response3 = wayback.execute(post, now);

    //    assertNotSame(response3, response2);

    System.currentTimeMillis();

    response1.getEntity().consumeContent();
    response2.getEntity().consumeContent();
    response3.getEntity().consumeContent();

    wayback.close();
}

From source file:com.aegiswallet.tasks.SendShamirValueTask.java

@Override
protected Object doInBackground(Object[] objects) {

    httpclient = new DefaultHttpClient();
    httppost = new HttpPost(Constants.AEGIS_SITE);

    Log.d(TAG, "sending shamir");
    try {//from  w  w w  .j  av  a 2 s. com
        // Add your data

        TelephonyManager tManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String uid = tManager.getDeviceId();

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("device", uid));
        nameValuePairs.add(new BasicNameValuePair("message", x3Value));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        int statusCode = response.getStatusLine().getStatusCode();

        Log.d(TAG, "response for shamir: " + statusCode);

        if (statusCode != 200) {
            //TODO: did not succeed
        } else {
            //Means we have successfully exported the key to BitcoinSecurityProject.org
            application.getPrefs().edit().remove(Constants.SHAMIR_EXPORTED_KEY).commit();
        }

    } catch (ClientProtocolException e) {
        Log.d(TAG, e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, e.getMessage());
    }
    return null;
}

From source file:eu.diacron.crawlservice.app.Util.java

public static String getCrawlid(URL urltoCrawl) {
    String crawlid = "";
    System.out.println("start crawling page");

    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(Configuration.REMOTE_CRAWLER_USERNAME,
                    Configuration.REMOTE_CRAWLER_PASS));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {//  ww w  .ja  v a 2  s  .c o m
        //HttpPost httppost = new HttpPost("http://diachron.hanzoarchives.com/crawl");
        HttpPost httppost = new HttpPost(Configuration.REMOTE_CRAWLER_URL_CRAWL_INIT);

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("name", UUID.randomUUID().toString()));
        urlParameters.add(new BasicNameValuePair("scope", "page"));
        urlParameters.add(new BasicNameValuePair("seed", urltoCrawl.toString()));

        httppost.setEntity(new UrlEncodedFormEntity(urlParameters));

        System.out.println("Executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println("----------------------------------------");

            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                crawlid = inputLine;
            }
            in.close();
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } catch (IOException ex) {
        Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            httpclient.close();
        } catch (IOException ex) {
            Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return crawlid;
}

From source file:org.blanco.techmun.android.misc.AuthTask.java

@Override
protected Boolean doInBackground(String... params) {
    if (params.length != 2) {
        throw new RuntimeException(
                "Parameters for AuthTask should be exactly 2. " + "String user, String password");
    }//w ww.jav  a2 s .co  m
    try {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        byte[] pbytes = digest.digest(params[1].getBytes());
        String md5password = new String(pbytes);
        HttpPost post = new HttpPost("http://tec-ch-mun-2011.herokuapp.com/application/autenticarUsuario");
        List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
        parameters.add(new BasicNameValuePair("user", params[0]));
        parameters.add(new BasicNameValuePair("md5password", md5password));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters);
        post.setEntity(entity);
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(post);
        boolean result = false;
        switch (response.getStatusLine().getStatusCode()) {
        case 200:
            Log.i("techmun", "Authentication request returned OK");
            result = true;
            break;
        default:
            Log.i("techmun", "Authentication request returned: " + response.getStatusLine().getStatusCode());
            result = false;
        }
        //client.close();
        return result;
    } catch (NoSuchAlgorithmException e) {
        Log.e("techmun", "Error geting md5 instance", e);
    } catch (UnsupportedEncodingException e) {
        Log.e("techmun", "Error preparing entity for autentication", e);
    } catch (IOException e) {
        Log.e("techmun", "Error sending autentication form", e);
    }
    return false;
}

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

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

    try {/*  w w  w  .  j a v  a2s. co m*/
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair("method", "search_samples"));
        params.add(new BasicNameValuePair("username", _username));
        params.add(new BasicNameValuePair("password", _password));

        if (_searchFilterString != null)
            params.add(new BasicNameValuePair("query", _searchFilterString));
        else
            params.add(new BasicNameValuePair("query", ""));

        params.add(new BasicNameValuePair("start", String.valueOf(_startRecord)));
        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 ExportSamplesResponse(_export, handler.handleResponse(response), status.getStatusCode(),
                    job);
        else
            return new ExportSamplesResponse(_export, status.getReasonPhrase(), status.getStatusCode(), job);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:addresspager.com.licenseinandroid.MainActivity.java

@Override
protected String doInBackground(String... te) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://10.0.2.2/ksource/index.php");
    List<NameValuePair> valobj = new ArrayList<NameValuePair>(2);
    valobj.add(new BasicNameValuePair("email", "sriram@gmail.com"));
    valobj.add(new BasicNameValuePair("user", "praveen.com"));
    try {// w w w .j  a  v a 2s . co  m
        this.log("backend server connection started");
        post.setEntity(new UrlEncodedFormEntity(valobj));
        HttpResponse ree = client.execute(post);
        String t = EntityUtils.toString(ree.getEntity());
        this.result = t;
        this.log("backend server connection ok..");
    } catch (UnsupportedEncodingException e) {
        this.result = "encoding exception";
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        this.result = "protocal exception";
        e.printStackTrace();
    } catch (IOException e) {
        this.result = "IO exception " + e.getMessage();
        e.printStackTrace();
    }
    return null;
}

From source file:D_common.E_xample.HttpClientExample.java

private void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";

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

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

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
    urlParameters.add(new BasicNameValuePair("cn", ""));
    urlParameters.add(new BasicNameValuePair("locale", ""));
    urlParameters.add(new BasicNameValuePair("caller", ""));
    urlParameters.add(new BasicNameValuePair("num", "12345"));

    post.setEntity(new UrlEncodedFormEntity(urlParameters));

    HttpResponse response = client.execute(post);
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + post.getEntity());
    System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

    Header[] headers = response.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        System.out.println(headers[i].getName() + ": " + headers[i].getValue());
    }/*from w  w  w  . j a  v a2  s.  com*/

    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());

}