Example usage for org.apache.http.client.entity UrlEncodedFormEntity setContentType

List of usage examples for org.apache.http.client.entity UrlEncodedFormEntity setContentType

Introduction

In this page you can find the example usage for org.apache.http.client.entity UrlEncodedFormEntity setContentType.

Prototype

public void setContentType(Header header) 

Source Link

Usage

From source file:com.ninehcom.userinfo.util.HttpUtils.java

/**
 * post form/*  w ww.  j  a v  a 2s . com*/
 * 
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param bodys
 * @return
 * @throws Exception
 */
public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers,
        Map<String, String> querys, Map<String, String> bodys) throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPost request = new HttpPost(buildUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }

    if (bodys != null) {
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

        for (String key : bodys.keySet()) {
            nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
        }
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
        formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
        request.setEntity(formEntity);
    }

    return httpClient.execute(request);
}

From source file:com.investoday.code.util.aliyun.api.gateway.util.HttpUtil.java

/**
 * FormEntity//from   www .j a  v a2s.  co  m
 * @param formParam
 * @return
 * @throws UnsupportedEncodingException
 */
private static UrlEncodedFormEntity buildFormEntity(Map<String, String> formParam)
        throws UnsupportedEncodingException {
    if (formParam != null) {
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

        for (String key : formParam.keySet()) {
            nameValuePairList.add(new BasicNameValuePair(key, formParam.get(key)));
        }
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList);
        formEntity.setContentType(ContentType.CONTENT_TYPE_FORM);
        return formEntity;
    }

    return null;
}

From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java

public static InputStream postDataRequestAndGetStream(String url, String contentType, int networkTimeout,
        List<NameValuePair> params) throws IllegalStateException, ClientProtocolException, IOException {
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
    entity.setContentType(contentType);

    HttpParams httpParameters = HttpHelpers.getConnectionParameters(networkTimeout);
    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("Accept-Encoding", "gzip");

    httpPost.setEntity(entity);//from  ww w.j a  va 2 s .co m
    return getInputStream(httpClient.execute(httpPost));
}

From source file:com.lostad.app.base.util.RequestUtil.java

public static String putForm(String url, List<NameValuePair> params, String token, boolean isSingleton)
        throws Exception {
    String json = null;/*www . j a v  a2  s  .  c o m*/
    HttpClient client = HttpClientManager.getHttpClient(isSingleton);
    HttpEntity resEntity = null;
    HttpPut put = new HttpPut(url);
    put.addHeader("token", token);
    try {
        put.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        if (params != null) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
            if (params != null) {
                entity.setContentEncoding(HTTP.UTF_8);
                entity.setContentType("application/x-www-form-urlencoded");
            }
            put.setEntity(entity);
        }

        HttpResponse response = client.execute(put, new BasicHttpContext());
        resEntity = response.getEntity();
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 200
            // ?
            json = EntityUtils.toString(resEntity);
        }
    } catch (Exception e) {
        if (put != null) {
            put.abort();//
        }
        throw e;
    } finally {

        if (resEntity != null) {
            try {
                resEntity.consumeContent();//?

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        client.getConnectionManager().closeExpiredConnections();
        ///client.getConnectionManager().shutdown();
    }
    return json;

}

From source file:cn.tc.ulife.platform.msg.http.util.HttpUtil.java

/**
 * FormEntity/*from   w  ww.j a v  a 2 s . c om*/
 * 
 * @param formParam
 * @return
 * @throws UnsupportedEncodingException
 */
private static UrlEncodedFormEntity buildFormEntity(Map<String, String> formParam)
        throws UnsupportedEncodingException {
    if (formParam != null) {
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

        for (String key : formParam.keySet()) {
            nameValuePairList.add(new BasicNameValuePair(key, formParam.get(key)));
        }
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, Constants.ENCODING);
        formEntity.setContentType(ContentType.CONTENT_TYPE_FORM);
        return formEntity;
    }

    return null;
}

From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java

public static InputStream postDataRequestAndGetStream(String url, UrlEncodedFormEntity formEntity,
        String contentType, int networkTimeout)
        throws IllegalStateException, ClientProtocolException, IOException {
    HttpParams httpParameters = HttpHelpers.getConnectionParameters(networkTimeout);
    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpPost httpPost = new HttpPost(url);
    HttpHelpers.addCommonHeaders(httpPost);
    formEntity.setContentType(contentType);
    formEntity.setContentEncoding(HTTP.UTF_8);
    httpPost.setEntity(formEntity);/* w  w w  .  j  a va 2  s  .  c om*/
    httpPost.addHeader("HTTP-Version", "HTTP/1.0");
    httpPost.addHeader("Accept-Encoding", "gzip");
    httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset = UTF-8");

    HttpResponse res = httpClient.execute(httpPost);

    return getInputStream(res);
}

From source file:org.forgerock.openam.mobile.commons.FormRestRequest.java

/**
 * Alters the request to insert additional HTTP POST x-www-form-urlencoded data
 *//*  w w  w. j  a v a2s . c  om*/
public void insertData(HashMap<String, String> formParameters) {

    if (formParameters == null) {
        return;
    }

    HttpPost request = getRequest();

    try {
        List<NameValuePair> data = new ArrayList<NameValuePair>();

        for (String s : formParameters.keySet()) {
            NameValuePair nvp = new BasicNameValuePair(s, formParameters.get(s));
            data.add(nvp);
        }

        UrlEncodedFormEntity formData = new UrlEncodedFormEntity(data);

        formData.setContentType(CONTENT_TYPE);
        request.setEntity(formData);
    } catch (UnsupportedEncodingException e) {
        fail(TAG, "Unable to set entity.");
    }
}

From source file:com.microsoft.live.TokenRequest.java

/**
 * Performs the Token Request and returns the OAuth server's response.
 *
 * @return The OAuthResponse from the server
 * @throws LiveAuthException if there is any exception while executing the request
 *                           (e.g., IOException, JSONException)
 */// www  .  j a v  a  2s. co m
public OAuthResponse execute() throws LiveAuthException {
    final Uri requestUri = Config.INSTANCE.getOAuthTokenUri();

    final HttpPost request = new HttpPost(requestUri.toString());

    final List<NameValuePair> body = new ArrayList<NameValuePair>();
    body.add(new BasicNameValuePair(OAuth.CLIENT_ID, this.clientId));

    // constructBody allows subclasses to add to body
    this.constructBody(body);

    try {
        final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(body, HTTP.UTF_8);
        entity.setContentType(CONTENT_TYPE);
        request.setEntity(entity);
    } catch (UnsupportedEncodingException e) {
        throw new LiveAuthException(ErrorMessages.CLIENT_ERROR, e);
    }

    final HttpResponse response;
    try {
        response = this.client.execute(request);
    } catch (ClientProtocolException e) {
        throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
    } catch (IOException e) {
        throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
    }

    final HttpEntity entity = response.getEntity();
    final String stringResponse;
    try {
        stringResponse = EntityUtils.toString(entity);
    } catch (IOException e) {
        throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
    }

    final JSONObject jsonResponse;
    try {
        jsonResponse = new JSONObject(stringResponse);
    } catch (JSONException e) {
        throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
    }

    if (OAuthErrorResponse.validOAuthErrorResponse(jsonResponse)) {
        return OAuthErrorResponse.createFromJson(jsonResponse);
    } else if (OAuthSuccessfulResponse.validOAuthSuccessfulResponse(jsonResponse)) {
        return OAuthSuccessfulResponse.createFromJson(jsonResponse);
    } else {
        throw new LiveAuthException(ErrorMessages.SERVER_ERROR);
    }
}

From source file:com.microsoft.services.msa.TokenRequest.java

/**
 * Performs the Token Request and returns the OAuth server's response.
 *
 * @return The OAuthResponse from the server
 * @throws LiveAuthException if there is any exception while executing the request
 *                           (e.g., IOException, JSONException)
 *///from  ww w.  j  av  a  2 s .  co  m
public OAuthResponse execute() throws LiveAuthException {
    final Uri requestUri = mOAuthConfig.getTokenUri();

    final HttpPost request = new HttpPost(requestUri.toString());

    final List<NameValuePair> body = new ArrayList<NameValuePair>();
    body.add(new BasicNameValuePair(OAuth.CLIENT_ID, this.clientId));

    // constructBody allows subclasses to add to body
    this.constructBody(body);

    try {
        final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(body, HTTP.UTF_8);
        entity.setContentType(CONTENT_TYPE);
        request.setEntity(entity);
    } catch (UnsupportedEncodingException e) {
        throw new LiveAuthException(ErrorMessages.CLIENT_ERROR, e);
    }

    final HttpResponse response;
    try {
        response = this.client.execute(request);
    } catch (ClientProtocolException e) {
        throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
    } catch (IOException e) {
        throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
    }

    final HttpEntity entity = response.getEntity();
    final String stringResponse;
    try {
        stringResponse = EntityUtils.toString(entity);
    } catch (IOException e) {
        throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
    }

    final JSONObject jsonResponse;
    try {
        jsonResponse = new JSONObject(stringResponse);
    } catch (JSONException e) {
        throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
    }

    if (OAuthErrorResponse.validOAuthErrorResponse(jsonResponse)) {
        return OAuthErrorResponse.createFromJson(jsonResponse);
    } else if (OAuthSuccessfulResponse.validOAuthSuccessfulResponse(jsonResponse)) {
        return OAuthSuccessfulResponse.createFromJson(jsonResponse);
    } else {
        throw new LiveAuthException(ErrorMessages.SERVER_ERROR);
    }
}

From source file:de.boksa.rt.rest.RTRESTClient.java

private RTRESTResponse getResponse(String url, List<NameValuePair> params) throws IOException {
    HttpPost postRequest = new HttpPost(this.getRestInterfaceBaseURL() + url);
    UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
    postEntity.setContentType("application/x-www-form-urlencoded");

    postRequest.setEntity(postEntity);//from   w  ww  .  j av  a  2s.  c om

    HttpResponse httpResponse = this.httpClient.execute(postRequest);

    String responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), HTTP.UTF_8);

    String[] responseSplit = responseBody.split("\n", 2);

    String header = responseSplit[0];

    String body = "";

    if (responseSplit.length == 2) {
        body = responseSplit[1];
    }

    Matcher metaMatcher = PATTERN_RESPONSE_META.matcher(header);

    if (metaMatcher.matches()) {
        RTRESTResponse response = new RTRESTResponse();
        response.setVersion(metaMatcher.group(1));
        response.setStatusCode(Long.valueOf(metaMatcher.group(2)));
        response.setStatusMessage(metaMatcher.group(3));
        response.setBody(body);
        return response;
    } else {
        System.err.println("not matched");
    }

    return new RTRESTResponse();
}