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.ammobyte.radioreddit.api.PerformLogin.java

@Override
protected Boolean doInBackground(String... params) {
    final String username = params[0];
    final String password = params[1];

    if (username == null || password == null || username.length() == 0 || password.length() == 0) {
        return false;
    }/*from  w w w .j ava  2s .  c o m*/

    // Prepare POST, execute it, parse response as JSON
    JSONObject response = null;
    try {
        final HttpClient httpClient = new DefaultHttpClient();
        final HttpPost httpPost = new HttpPost("https://ssl.reddit.com/api/login");
        final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("user", username));
        nameValuePairs.add(new BasicNameValuePair("passwd", password));
        nameValuePairs.add(new BasicNameValuePair("api_type", "json"));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        httpPost.setHeader("User-Agent", RedditApi.USER_AGENT);
        final HttpResponse httpResponse = httpClient.execute(httpPost);
        final String responseBody = EntityUtils.toString(httpResponse.getEntity());
        if (MusicService.DEBUG) {
            Log.i(RedditApi.TAG, "Reddit API login response: " + responseBody);
        }
        response = new JSONObject(responseBody);
        response = response.getJSONObject("json");
    } catch (UnsupportedEncodingException e) {
        Log.i(RedditApi.TAG, "UnsupportedEncodingException while performing login", e);
        return false;
    } catch (ClientProtocolException e) {
        Log.i(RedditApi.TAG, "ClientProtocolException while performing login", e);
        return false;
    } catch (IOException e) {
        Log.i(RedditApi.TAG, "IOException while performing login", e);
        return false;
    } catch (ParseException e) {
        Log.i(RedditApi.TAG, "ParseException while performing login", e);
        return false;
    } catch (JSONException e) {
        Log.i(RedditApi.TAG, "JSONException while performing login", e);
        return false;
    }

    // Check for failure 
    if (response == null) {
        Log.i(RedditApi.TAG, "Response was null while performing login");
        return false;
    }

    // Check for errors
    final JSONArray errors = response.optJSONArray("errors");
    if (errors == null || errors.length() > 0) {
        Log.i(RedditApi.TAG, "Response has errors while performing login");
        return false;
    }

    // Check for data
    final JSONObject data = response.optJSONObject("data");
    if (data == null) {
        Log.i(RedditApi.TAG, "Response missing data while performing login");
        return false;
    }

    // Get modhash and cookie from data
    mUser = username;
    mModhash = data.optString("modhash");
    mCookie = data.optString("cookie");
    if (mModhash.length() == 0 || mCookie.length() == 0) {
        Log.i(RedditApi.TAG, "Response missing modhash/cookie while performing login");
        return false;
    }

    return true;
}

From source file:ru.elifantiev.yandex.oauth.AsyncContinuationHandler.java

@Override
protected AuthResult doInBackground(Uri... params) {

    String code, error;//from  w  w w  .  ja  v a  2 s  . c  o  m

    if (params.length == 3) {
        // TODO: Add redir URL checking
        if ((code = params[2].getQueryParameter("code")) == null) {
            if ((error = params[2].getQueryParameter("error")) == null) {
                return new AuthResult("Unknown error");
            } else {
                return new AuthResult(error);
            }
        }
    } else
        return new AuthResult("Wrong parameters count");

    HttpClient client = SSLHttpClientFactory.getNewHttpClient();
    HttpPost method = new HttpPost(params[0].buildUpon().path("/oauth/token").build().toString());

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
    nameValuePairs.add(new BasicNameValuePair("code", code));
    nameValuePairs.add(new BasicNameValuePair("client_id", clientId));
    nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
    nameValuePairs.add(new BasicNameValuePair("redirect_uri", params[1].toString()));
    try {
        method.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e) {
        return new AuthResult(e.getMessage());
    }

    String token = null;
    try {
        HttpResponse httpResponse = client.execute(method);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == 200 || statusCode == 400) {
            JSONObject response = (JSONObject) (new JSONTokener(EntityUtils.toString(httpResponse.getEntity()))
                    .nextValue());
            if (response.has("access_token"))
                token = response.getString("access_token");
            else if (response.has("error"))
                return new AuthResult(response.getString("error"));
        } else
            return new AuthResult("Call failed. Returned HTTP response code " + String.valueOf(statusCode));
    } catch (IOException e) {
        return new AuthResult(e.getMessage());
    } catch (JSONException e) {
        return new AuthResult(e.getMessage());
    }

    return new AuthResult(new AccessToken(token));
}

From source file:com.buddy.sdk.web.BuddyWebWrapper.java

public static void MakeRequest(String apiCall, List<NameValuePair> params, final Object state,
        final OnResponseCallback callback) {
    UrlEncodedFormEntity entity = null;//from  w  ww  .jav a2s. c  o  m
    try {
        entity = new UrlEncodedFormEntity(params);
    } catch (UnsupportedEncodingException e1) {
        BuddyCallbackParams callbackParams = new BuddyCallbackParams(e1, "");
        callback.OnResponse(callbackParams, state);
    }

    String url = urlType + endpointUrl + "?" + apiCall;

    AsyncHttpClient client = BuddyHttpClientFactory.getHttpClient();

    client.post(null, url, entity, "application/x-www-form-urlencoded", new AsyncHttpResponseHandler() {
        @Override
        public void onStart() {
            Log.d(TAG, "OnStart");
        }

        @Override
        public void onSuccess(String success) {
            Log.d(TAG + "-POST SUCCESS", success);
            if (callback != null) {
                BuddyCallbackParams callbackParams = null;
                Exception exception = Utils.ProcessStandardErrors(success);
                if (exception == null) {
                    callbackParams = new BuddyCallbackParams();
                    callbackParams.response = success;
                } else {
                    callbackParams = new BuddyCallbackParams(exception, success);
                }
                callback.OnResponse(callbackParams, state);
            }
            Log.d(TAG, "OnSuccess");
        }

        @Override
        public void onFailure(Throwable e, String response) {
            if (callback != null) {
                BuddyCallbackParams callbackParams = new BuddyCallbackParams(e, response);
                callback.OnResponse(callbackParams, state);
            }
            Log.d(TAG, "OnFailure");
        }

    });
}

From source file:com.rfcx.cellmapping.tasks.RequestTask.java

@Override
protected String doInBackground(String... uri) {

    HttpClient httpclient = new DefaultHttpClient();

    // add request params
    StringBuffer url = new StringBuffer(uri[0]).append("?");
    //   .append(URLEncodedUtils.format(getParams(), "UTF-8"));

    //HttpGet _get = new HttpGet(url.toString());

    HttpPost _post = new HttpPost(url.toString());

    Log.i("url---->", url.toString());

    try {// www  .j a  v  a2 s. c om
        _post.setEntity(new UrlEncodedFormEntity(getParams()));

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

    // add request headers
    ArrayList<NameValuePair> _headers = getHeaders();
    for (NameValuePair pair : _headers) {
        _post.addHeader(pair.getName(), pair.getValue());
    }

    HttpResponse response;
    String responseString = null;
    // execute
    try {
        response = httpclient.execute(_post);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();

            if (isCancelled()) {
                rsh.onError("Task cancel");
            }

        } else {
            //Closes the connection.
            response.getEntity().getContent().close();
            Log.i("error", statusLine.getReasonPhrase());
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        //rsh.onError(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        //rsh.onError(e.getMessage());      
    }
    return responseString;
}

From source file:apimanager.ZohoReportsAPIManager.java

public void postaddSingleRow() {

    String URL = "https://reportsapi.zoho.com/api/harshavardhan.r@zohocorp.com/Test/Name_password?ZOHO_ACTION=ADDROW&ZOHO_OUTPUT_FORMAT=json&ZOHO_ERROR_FORMAT=json&authtoken=7ed717b94bc30455aad11ce5d31d34f9&ZOHO_API_VERSION=1.0";

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost post = new HttpPost(
            "https://reportsapi.zoho.com/api/harshavardhan.r@zohocorp.com/Test/Name_password?ZOHO_ACTION=ADDROW&ZOHO_OUTPUT_FORMAT=json&ZOHO_ERROR_FORMAT=json&authtoken=7ed717b94bc30455aad11ce5d31d34f9&ZOHO_API_VERSION=1.0");

    try {//from   www .  j  a  v  a 2 s . c o m
        List<NameValuePair> nameValuePairs = new ArrayList<>(2);
        nameValuePairs.add(new BasicNameValuePair("Name", "harshaViaPostnet"));
        nameValuePairs.add(new BasicNameValuePair("Password", "harshaviaPost123net"));
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
        }

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

From source file:com.sunhz.projectutils.httputils.HttpClientUtils.java

/**
 * post access to the network, you need to use in the sub-thread
 *
 * @param url    url//w w w . j a  v  a  2s.co m
 * @param params params
 * @return response inputStream
 * @throws IOException In the case of non-200 status code is returned, it would have thrown
 */
public static InputStream postInputStream(String url, Map<String, String> params) throws IOException {
    List<NameValuePair> list = new ArrayList<NameValuePair>();
    if (params != null && !params.isEmpty()) {
        for (Map.Entry<String, String> entry : params.entrySet()) {
            list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
    }
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list);
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(entity);
    org.apache.http.client.HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
            Constant.TimeInApplication.NET_TIMEOUT);
    client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, Constant.TimeInApplication.NET_TIMEOUT);
    HttpResponse response = client.execute(httpPost);
    if (response.getStatusLine().getStatusCode() == 200) {
        return response.getEntity().getContent();
    } else {
        throw new IllegalArgumentException("postInputStreamInSubThread response status code is "
                + response.getStatusLine().getStatusCode());
    }

}

From source file:com.updater.ota.GCMIntentService.java

@Override
protected void onRegistered(Context ctx, String regID) {
    Log.v("OTAUpdater::GCMRegister", "GCM registered - ID=" + regID);
    ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("do", "register"));
    params.add(new BasicNameValuePair("reg_id", regID));
    params.add(new BasicNameValuePair("device", android.os.Build.DEVICE.toLowerCase()));
    params.add(new BasicNameValuePair("rom_id", Utils.getRomID()));
    params.add(new BasicNameValuePair("device_id",
            ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId()));

    try {// ww  w.java  2  s  .  c om
        HttpClient http = new DefaultHttpClient();
        HttpPost req = new HttpPost(Config.GCM_REGISTER_URL);
        req.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse r = http.execute(req);
        int status = r.getStatusLine().getStatusCode();
        HttpEntity e = r.getEntity();
        if (status == 200) {
            String data = EntityUtils.toString(e);
            if (data.length() == 0) {
                Log.w("OTA::GCMRegister", "No response to registration");
                return;
            }
            JSONObject json = new JSONObject(data);

            if (json.length() == 0) {
                Log.w("OTA::GCMRegister", "Empty response to registration");
                return;
            }

            if (json.has("error")) {
                Log.e("OTA::GCMRegister", json.getString("error"));
                return;
            }

            RomInfo info = new RomInfo(json.getString("rom"), json.getString("version"),
                    json.getString("changelog"), json.getString("url"), json.getString("md5"),
                    Utils.parseDate(json.getString("date")));

            if (Utils.isUpdate(info)) {
                Config.getInstance(getApplicationContext()).storeUpdate(info);
                Utils.showUpdateNotif(getApplicationContext(), info);
            } else {
                Config.getInstance(getApplicationContext()).clearStoredUpdate();
            }
        } else {
            if (e != null)
                e.consumeContent();
            Log.w("OTA::GCMRegistr", "registration response " + status);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.sling.distribution.it.DistributionUtils.java

public static String assertPostResourceWithParameters(SlingInstance slingInstance, int status, String path,
        String... parameters) throws IOException {
    Request request = slingInstance.getRequestBuilder().buildPostRequest(path);

    if (parameters != null) {
        assertEquals(0, parameters.length % 2);
        List<NameValuePair> valuePairList = new ArrayList<NameValuePair>();

        for (int i = 0; i < parameters.length; i += 2) {
            valuePairList.add(new BasicNameValuePair(parameters[i], parameters[i + 1]));
        }/*  ww w  .j  a v a 2s. com*/
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairList);
        request.withEntity(entity);
    }

    return slingInstance.getRequestExecutor()
            .execute(request.withCredentials(DISTRIBUTOR_USER, DISTRIBUTOR_PASSWORD)).assertStatus(status)
            .getContent();
}

From source file:org.apache.sling.resourceaccesssecurity.it.ResourceAccessSecurityTestBase.java

protected String testUpdate(String username, String password, String path, int expectedStatus,
        String... expectedContent) throws Exception {
    String addedValue = "addedValue" + UUID.randomUUID().toString();
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("addedProperty", addedValue));

    if (username == null) {
        // call without credentials
        getRequestExecutor()//ww  w.  j  ava 2 s.c o m
                .execute(
                        getRequestBuilder().buildPostRequest(path).withEntity(new UrlEncodedFormEntity(params)))
                .assertStatus(expectedStatus).assertContentContains(expectedContent);
    } else {
        // call with credentials
        getRequestExecutor()
                .execute(
                        getRequestBuilder().buildPostRequest(path).withEntity(new UrlEncodedFormEntity(params)))
                .assertStatus(expectedStatus).assertContentContains(expectedContent);

    }

    return addedValue;
}

From source file:com.oneteam.framework.android.net.HttpPostConnection.java

@Override
public void connect() {

    HttpPost httpPost = new HttpPost(mUrl);

    if (mParamsMap != null && mParamsMap.size() > 0) {

        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(mParamsMap.values());

        try {//w  w  w.j ava2 s. c  o m

            httpPost.setEntity(new UrlEncodedFormEntity(params));

        } catch (UnsupportedEncodingException e) {

            Logger.w("Failure while establishing url connection as unsupported encoding error > "
                    + e.getMessage());

            e.printStackTrace();
        }
    }

    super.connect(httpPost);
}