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:me.chunsheng.ebooks.hackerearth.api.requests.BaseRequest.java

protected String sendRequest(final String endpoint, final List<NameValuePair> options) {
    try {//from   w ww  .  ja va 2 s  . c o  m
        HttpPost httpPost = new HttpPost(endpoint);
        httpPost.setEntity(new UrlEncodedFormEntity(options));
        httpPost.setHeader(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF_8");
        //httpPost.setHeader("Content-type", "application/json");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(httpPost);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer resultBuffer = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            resultBuffer.append(line);
        }
        return resultBuffer.toString();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.dimasdanz.kendalipintu.util.JSONParser.java

public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
    try {//  ww w  .ja  v a  2s  .c om
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(httpParameters, so_timeout);
        HttpConnectionParams.setConnectionTimeout(httpParameters, co_timeout);
        if (method == "POST") {
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        } else if (method == "GET") {
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }
    } catch (SocketTimeoutException e) {
        Log.e("SocketTimeoutException", "SocketTimeoutException");
        e.printStackTrace();
        return null;
    } catch (UnsupportedEncodingException e) {
        Log.e("UnsupportedEncodingException", "UnsupportedEncodingException");
        e.printStackTrace();
        return null;
    } catch (ClientProtocolException e) {
        Log.e("ClientProtocolException", "ClientProtocolException");
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        Log.e("IOException", "IOException");
        e.printStackTrace();
        return null;
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Buffer Error :  " + e.toString());
        return null;
    }

    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
        return null;
    }
    return jObj;
}

From source file:org.opencastproject.gstreamer.remote.GStreamerServiceRemoteImpl.java

/**
 * {@inheritDoc}//from ww w  . j av a2  s .  c  o m
 * 
 * @see org.opencastproject.gstreamer.api.GStreamerService#launch(org.opencastproject.mediapackage.MediaPackage,
 *      java.lang.String, java.lang.String)
 */
public Job launch(MediaPackage mediapackage, String launch, String outputFiles)
        throws GStreamerLaunchException {
    HttpPost post = new HttpPost("/launch");
    try {
        List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("mediapackage", MediaPackageParser.getAsXml(mediapackage)));
        params.add(new BasicNameValuePair("launch", launch));
        params.add(new BasicNameValuePair("outputFiles", outputFiles));
        post.setEntity(new UrlEncodedFormEntity(params));
    } catch (Exception e) {
        throw new GStreamerLaunchException("Unable to assemble a remote composer request for track " + e);
    }
    HttpResponse response = null;
    try {
        response = getResponse(post);
        if (response != null) {
            String content = EntityUtils.toString(response.getEntity());
            Job r = JobParser.parseJob(content);
            logger.info("Encoding job {} started on a remote composer", r.getId());
            return r;
        }
    } catch (Exception e) {
        throw new GStreamerLaunchException("Unable to encode track " + " using a remote composer service", e);
    } finally {
        closeConnection(response);
    }
    throw new GStreamerLaunchException("Unable to encode track " + " using a remote composer service");
}

From source file:org.megam.api.http.TransportMachinery.java

public static TransportResponse put(TransportTools nuts) throws ClientProtocolException, IOException {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPut httpput = new HttpPut(nuts.urlString());

    if (nuts.headers() != null) {
        for (Map.Entry<String, String> headerEntry : nuts.headers().entrySet()) {
            httpput.addHeader(headerEntry.getKey(), headerEntry.getValue());
        }//from w w  w. j a  v  a2  s. c om
    }

    if (nuts.pairs() != null && (nuts.contentType() == null)) {
        httpput.setEntity(new UrlEncodedFormEntity(nuts.pairs()));
    }

    if (nuts.contentType() != null) {
        httpput.setEntity(new StringEntity(nuts.contentString(), nuts.contentType()));
    }

    TransportResponse transportResp = null;
    try {
        HttpResponse httpResp = httpclient.execute(httpput);
        transportResp = new TransportResponse(httpResp.getStatusLine(), httpResp.getEntity(),
                httpResp.getLocale());
    } finally {
        httpput.releaseConnection();
    }
    return transportResp;

}

From source file:com.gmail.at.faint545.tasks.QueueDownloadTask.java

@Override
protected String doInBackground(Void... params) {
    HttpClient client = new DefaultHttpClient();
    HttpPost request = new HttpPost(url);

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

    try {//  w w  w .j  av a  2  s  .c  o m
        request.setEntity(new UrlEncodedFormEntity(arguments));
        HttpResponse result = client.execute(request);
        InputStream inStream = result.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(inStream), 8);
        StringBuilder jsonStringBuilder = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            if (line.length() > 0) {
                jsonStringBuilder.append(line);
            }
        }
        br.close();
        inStream.close();
        return jsonStringBuilder.toString();
    } catch (ClientProtocolException e) {
        return ClientProtocolException.class.getName();
    } catch (IOException e) {
        return ClientProtocolException.class.getName();
    }
}

From source file:vazkii.psi.client.core.helper.SharingHelper.java

public static String uploadImage(String title, String export) {
    try {//from w ww.  j  av a2 s. com
        String desc = "Spell Code:\n\n" + export;
        HttpClient client = HttpClients.createDefault();

        String url = "https://api.imgur.com/3/image";
        HttpPost post = new HttpPost(url);

        List<NameValuePair> list = new ArrayList();
        list.add(new BasicNameValuePair("type", "base64"));
        list.add(new BasicNameValuePair("image", takeScreenshot()));
        list.add(new BasicNameValuePair("name", title));
        list.add(new BasicNameValuePair("description", desc));

        post.setEntity(new UrlEncodedFormEntity(list));
        post.addHeader("Authorization", "Client-ID " + CLIENT_ID);

        HttpResponse res = client.execute(post);
        JsonObject resJson = new JsonParser().parse(EntityUtils.toString(res.getEntity())).getAsJsonObject();
        if (resJson.has("success") && resJson.get("success").getAsBoolean()) {
            JsonObject data = resJson.get("data").getAsJsonObject();
            String id = data.get("id").getAsString();

            return "https://imgur.com/" + id;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return "N/A";
}

From source file:org.mobicents.servlet.sip.restcomm.interpreter.http.HttpRequestDescriptor.java

public HttpUriRequest getHttpRequest()
        throws IllegalArgumentException, URISyntaxException, UnsupportedEncodingException {
    if ("GET".equalsIgnoreCase(method)) {
        final String query = URLEncodedUtils.format(parameters, "UTF-8");
        final URI uri = URIUtils.createURI(this.uri.getScheme(), this.uri.getHost(), this.uri.getPort(),
                this.uri.getPath(), query, null);
        return new HttpGet(uri);
    } else if ("POST".equalsIgnoreCase(method)) {
        final HttpPost post = new HttpPost(uri);
        post.setEntity(new UrlEncodedFormEntity(parameters));
        return post;
    } else {//from w  w w. j  a  v  a 2s .  c  o m
        throw new IllegalArgumentException(method + " is not a supported HTTP method.");
    }
}

From source file:cfappserver.Bot.java

public static String genData(String user, String pass, int semnum) {
    try {//  w  ww  .  j  a  v  a2  s.com
        String url = "https://home-access.cfisd.net/HomeAccess/Account/LogOn?ReturnUrl=%2fhomeaccess%2f";
        final HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(httpParams, 10000);
        HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
        HttpClient client = new DefaultHttpClient(httpParams);
        CookieStore httpCookieStore = new BasicCookieStore();
        HttpClientBuilder builder = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore);
        HttpPost post = new HttpPost(url);
        Scanner kk = new Scanner(System.in);
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("Database", "10"));
        urlParameters.add(new BasicNameValuePair("LogOnDetails.UserName", user));
        urlParameters.add(new BasicNameValuePair("LogOnDetails.Password", pass));

        post.setEntity(new UrlEncodedFormEntity(urlParameters));
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
        }

        response = client.execute(new HttpGet("https://home-access.cfisd.net/HomeAccess/Classes/Classwork"));
        rd = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));
        result = new StringBuffer();
        line = "";
        ClssPkg classpack = null;
        while ((line = rd.readLine()) != null) {
            if (line.contains("<li class=\"sg-banner-menu-element sg-menu-element-identity\">")) {
                classpack = new ClssPkg(rd.readLine().split("<|>")[2],semnum);
            }
        }
        if (classpack == null) {
            return "Wrong login";
        }
        getReport(client, classpack);
        getLunch(client, classpack);
        getAssignments(client, classpack);
        getAbsences(client, classpack, urlParameters);
        return classpack.toString();
    } catch (Exception ex) {
        Logger.getLogger(Bot.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "Wrong login";
}

From source file:ru.altruix.commons.android.WebServiceTaskHelper.java

@Override
public HttpResponse doResponse(final String aUrl) {

    // Use our connection and data timeouts as parameters for our
    // DefaultHttpClient
    HttpClient httpclient = new DefaultHttpClient(getHttpParams());

    HttpResponse response = null;//from w w  w .  j a  v a  2 s.c  o m

    try {
        switch (taskType) {

        case POST_TASK:
            HttpPost httppost = new HttpPost(aUrl);
            // Add parameters
            httppost.setEntity(new UrlEncodedFormEntity(params));

            response = httpclient.execute(httppost);
            break;
        case GET_TASK:
            HttpGet httpget = new HttpGet(aUrl);
            response = httpclient.execute(httpget);
            break;
        }
    } catch (Exception e) {

        Log.e(TAG, e.getLocalizedMessage(), e);

    }

    return response;
}