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.dedipower.portal.android.PortalAPI.java

public String Login(List<NameValuePair> Credentials) {
    // Create a new HttpClient and Post Header  
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("https://portal.dedipower.com/api.php?format=json&action=login");
    HttpResponse response = null;/*  w w  w .  jav a  2 s .  c  om*/
    JSONObject json;
    String Success;

    try {
        httppost.setEntity(new UrlEncodedFormEntity(Credentials));
        response = httpclient.execute(httppost);
    } catch (ClientProtocolException e) {
        return "Client Protocol Exception";
    } catch (IOException e) {
        return "Remote API Timed Out";
    }

    try {
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        response.getEntity().writeTo(outstream);
        json = new JSONObject(new String(outstream.toByteArray()));
    } catch (JSONException e) {
        //Log.e("APIFuncs",e.getMessage());
        return "JSON Parse Failure";
    } catch (IOException e) {
        return "JSON Parse IO Exception";
    }

    try {
        Success = json.getString("success");
    } catch (JSONException e) {
        return "Success Confirmation Failed";
    }

    if (Success == "true") {
        try {
            SessionID = json.getString("sessionid");
            return "true";
        } catch (JSONException e) {
            return "SessionID Confirmation Failed";
        }
    } else {
        try {
            return json.getString("msg");
        } catch (JSONException e) {
            return "Failure Message Failed";
        }
    }
}

From source file:att.jaxrs.client.Tag.java

public static long getExistingRecord(String tag_name) {

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("tag_name", tag_name));

    HttpResponse result;//from w  w  w . java  2s.  c om
    String resultStr;
    TagCollection tagCollection = new TagCollection();

    try {
        System.out.println("invoking last added: " + tag_name);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(Constants.SELECT_LAST_ADDED_TAG_RESOURCE);
        post.setEntity(new UrlEncodedFormEntity(urlParameters));
        result = httpClient.execute(post);
        System.out.println(Constants.RESPONSE_STATUS_CODE + result);
        resultStr = Util.getStringFromInputStream(result);

        tagCollection = Marshal.unmarshal(TagCollection.class, resultStr);

    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();

    }

    if (null != tagCollection.getTag()) {
        return tagCollection.getTag()[0].getTag_id();
    }
    return -1L;
}

From source file:com.splunk.shuttl.archiver.archive.ArchiveRestHandler.java

private static HttpUriRequest createBucketArchiveRequest(Bucket bucket) throws UnsupportedEncodingException {
    // CONFIG configure the host and port with a general solution.
    String requestString = "http://localhost:9090/" + ShuttlConstants.ENDPOINT_CONTEXT
            + ShuttlConstants.ENDPOINT_ARCHIVER + ShuttlConstants.ENDPOINT_BUCKET_ARCHIVER;

    HttpPost request = new HttpPost(requestString);

    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("path", bucket.getDirectory().getAbsolutePath()));
    params.add(new BasicNameValuePair("index", bucket.getIndex()));

    request.setEntity(new UrlEncodedFormEntity(params));
    return request;
}

From source file:siarhei.luskanau.gps.tracker.free.service.sync.tracking.json.SendJsonForm.java

public static void sendLocationsForm(Context context) throws Exception {
    ServerEntity serverEntity = AppSettings.getServerEntity(context);

    for (;;) {/*w w  w  .java  2s  .c  o  m*/
        List<LocationModel> locationEntities = LocationDAO.queryNextLocations(context, 100);
        if (locationEntities != null && locationEntities.size() > 0) {

            String requestJsonString = AppConstants.GSON.toJson(locationEntities);

            HttpPost httpPost = new HttpPost(serverEntity.server_address);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8");
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("track", requestJsonString));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            if (DEBUG) {
                Log.d(TAG, "Send request: " + httpPost.getURI() + " " + requestJsonString);
            }
            String responseJsonString = read(requestInputStream(httpPost));
            if (DEBUG) {
                Log.d(TAG, "Received response: " + responseJsonString);
            }

            SendLocationsResponseDTO statusResponse = AppConstants.GSON.fromJson(responseJsonString,
                    SendLocationsResponseDTO.class);
            if (statusResponse != null && statusResponse.success) {
                LocationDAO.deleteLocations(context, locationEntities);
                incPacketCounter(context, locationEntities.size());
                Log.d(context.getPackageName(),
                        "Packet is send: " + locationEntities.size() + " " + responseJsonString);
            } else {
                Log.e(context.getPackageName(), "Packet is not send: " + responseJsonString);
                break;
            }
        } else {
            break;
        }
    }
}

From source file:org.jboss.arquillian.ce.httpclient.HttpRequestImpl.java

public void setEntity(Map<String, String> form) throws IOException {
    if (request instanceof HttpEntityEnclosingRequest) {
        List<NameValuePair> params = new ArrayList<>();
        for (Map.Entry<String, String> entry : form.entrySet()) {
            params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }//from ww  w .j a v  a  2s .  c  o m
        HttpEntityEnclosingRequest.class.cast(request).setEntity(new UrlEncodedFormEntity(params));
    }
}

From source file:com.splunk.shuttl.server.mbeans.util.EndpointUtils.java

/**
 * Set data params to a post request.//from  ww w . j a  va 2s .co m
 */
public static void setParamsToPostRequest(HttpPost httpPost, List<BasicNameValuePair> postParams) {
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(postParams));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.networksaremadeofstring.pulsant.portal.PortalAPI.java

public String Login(List<NameValuePair> Credentials) {
    // Create a new HttpClient and Post Header  
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("https://portal.pulsant.com/api.php?format=json&action=login");
    HttpResponse response = null;//from www . ja v  a 2  s  . c  o  m
    JSONObject json;
    String Success;

    try {
        httppost.setEntity(new UrlEncodedFormEntity(Credentials));
        response = httpclient.execute(httppost);
    } catch (ClientProtocolException e) {
        return "Client Protocol Exception";
    } catch (IOException e) {
        e.printStackTrace();
        return "Remote API Timed Out";
    }

    try {
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        response.getEntity().writeTo(outstream);
        json = new JSONObject(new String(outstream.toByteArray()));
    } catch (JSONException e) {
        //Log.e("APIFuncs",e.getMessage());
        return "JSON Parse Failure";
    } catch (IOException e) {
        return "JSON Parse IO Exception";
    }

    try {
        Success = json.getString("success");
    } catch (JSONException e) {
        return "Success Confirmation Failed";
    }

    if (Success == "true") {
        try {
            SessionID = json.getString("sessionid");
            return "true";
        } catch (JSONException e) {
            return "SessionID Confirmation Failed";
        }
    } else {
        try {
            return json.getString("msg");
        } catch (JSONException e) {
            return "Failure Message Failed";
        }
    }
}

From source file:au.org.ncallister.goodbudget.tools.coms.GoodBudgetSession.java

public void login(String username, String password) throws IOException {
    if (client == null) {
        client = HttpClients.createDefault();
    }/*from   w  ww  .ja  va2s  . c o m*/

    HttpPost post = new HttpPost(BASE_URI.resolve(PATH_LOGIN));
    //      post.addHeader("Content-Type", "application/x-www-form-urlencoded");
    List<NameValuePair> postContent = new ArrayList<>();
    postContent.add(new BasicNameValuePair("_username", username));
    postContent.add(new BasicNameValuePair("_password", password));
    post.setEntity(new UrlEncodedFormEntity(postContent));

    CloseableHttpResponse response = client.execute(post, sessionContext);
    response.close();
}

From source file:com.ammobyte.radioreddit.api.PerformVote.java

@Override
protected Void doInBackground(String... params) {
    final String modhash = params[0];
    final String cookie = params[1];
    final String id = params[2];
    final String dir = params[3];

    if (MusicService.DEBUG) {
        Log.i(RedditApi.TAG,//  w  w w . j av a  2 s .  c o  m
                String.format("PerformVote args: modhash=%s cookie=%s id=%s dir=%s", modhash, cookie, id, dir));
    }

    // Prepare POST with cookie and execute it
    try {
        final HttpClient httpClient = new DefaultHttpClient();
        final HttpPost httpPost = new HttpPost("http://www.reddit.com/api/vote");
        final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("id", id));
        nameValuePairs.add(new BasicNameValuePair("dir", dir));
        nameValuePairs.add(new BasicNameValuePair("uh", modhash));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        // Using HttpContext, CookieStore, and friends didn't work
        httpPost.setHeader("Cookie", String.format("reddit_session=\"%s\"", cookie));
        httpPost.setHeader("User-Agent", RedditApi.USER_AGENT);
        if (MusicService.DEBUG) {
            // Do some extra work when debugging to print the response
            final ResponseHandler<String> responseHandler = new BasicResponseHandler();
            final String response = httpClient.execute(httpPost, responseHandler);
            Log.i(RedditApi.TAG, "Reddit vote response: " + response);
        } else {
            // Otherwise just assume everything works out for now
            // TODO: Check for error responses and inform user of the problem
            httpClient.execute(httpPost);
        }
    } catch (UnsupportedEncodingException e) {
        Log.i(RedditApi.TAG, "UnsupportedEncodingException while performing vote", e);
    } catch (ClientProtocolException e) {
        Log.i(RedditApi.TAG, "ClientProtocolException while performing vote", e);
    } catch (IOException e) {
        Log.i(RedditApi.TAG, "IOException while performing vote", e);
    } catch (ParseException e) {
        Log.i(RedditApi.TAG, "ParseException while performing vote", e);
    }

    return null;
}

From source file:eu.trentorise.smartcampus.ac.network.RemoteConnector.java

public static TokenData validateAccessCode(String service, String code, String clientId, String clientSecret,
        String scope, String redirectUri) throws AACException {
    final HttpResponse resp;
    Log.i(TAG, "validating code: " + code);
    //        String url = service + PATH_TOKEN+"?grant_type=authorization_code&code="+code+"&client_id="+clientId +"&client_secret="+clientSecret+"&redirect_uri="+redirectUri;
    //        if (scope != null) url+= "&scope="+scope;
    final HttpPost post = new HttpPost(service + PATH_TOKEN);
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("grant_type", "authorization_code"));
    params.add(new BasicNameValuePair("code", code));
    params.add(new BasicNameValuePair("client_id", clientId));
    params.add(new BasicNameValuePair("client_secret", clientSecret));
    params.add(new BasicNameValuePair("redirect_uri", redirectUri));
    if (scope != null)
        params.add(new BasicNameValuePair("scope", scope));

    post.setHeader("Accept", "application/json");
    try {//from  ww  w .j a  va2 s. com
        post.setEntity(new UrlEncodedFormEntity(params));
        resp = getHttpClient().execute(post);
        final String response = EntityUtils.toString(resp.getEntity());
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            TokenData data = TokenData.valueOf(response);
            Log.v(TAG, "Successful authentication");
            return data;
        }
        Log.e(TAG, "Error validating " + resp.getStatusLine());
        throw new AACException("Error validating " + resp.getStatusLine());
    } catch (final Exception e) {
        Log.e(TAG, "Exception when getting authtoken", e);
        throw new AACException(e);
    } finally {
        Log.v(TAG, "getAuthtoken completing");
    }
}