Search in sources :

Example 81 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project android-app by eoecn.

the class CustomHttpClient method PostFromWebByHttpClient.

/**
	 * HttpClient post方法
	 * 
	 * @param url
	 * @param nameValuePairs
	 * @return
	 */
public static String PostFromWebByHttpClient(Context context, String url, NameValuePair... nameValuePairs) {
    try {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        if (nameValuePairs != null) {
            for (int i = 0; i < nameValuePairs.length; i++) {
                params.add(nameValuePairs[i]);
            }
        }
        UrlEncodedFormEntity urlEncoded = new UrlEncodedFormEntity(params, CHARSET_UTF8);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(urlEncoded);
        HttpClient client = getHttpClient(context);
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new RuntimeException("请求失败");
        }
        HttpEntity resEntity = response.getEntity();
        return (resEntity == null) ? null : EntityUtils.toString(resEntity, CHARSET_UTF8);
    } catch (UnsupportedEncodingException e) {
        Log.w(TAG, e.getMessage());
        return null;
    } catch (ClientProtocolException e) {
        Log.w(TAG, e.getMessage());
        return null;
    } catch (IOException e) {
        throw new RuntimeException(context.getResources().getString(R.string.httpError), e);
    }
}
Also used : NameValuePair(org.apache.http.NameValuePair) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient)

Example 82 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project h2o-2 by h2oai.

the class GoogleAnalyticsThreadFactory method post.

@SuppressWarnings({ "rawtypes" })
public GoogleAnalyticsResponse post(GoogleAnalyticsRequest request) {
    GoogleAnalyticsResponse response = new GoogleAnalyticsResponse();
    if (!config.isEnabled()) {
        return response;
    }
    BasicHttpResponse httpResponse = null;
    try {
        List<NameValuePair> postParms = new ArrayList<NameValuePair>();
        //Log.debug("GA Processing " + request);
        //Process the parameters
        processParameters(request, postParms);
        //Process custom dimensions
        processCustomDimensionParameters(request, postParms);
        //Process custom metrics
        processCustomMetricParameters(request, postParms);
        //Log.debug("GA Processed all parameters and sending the request " + postParms);
        HttpPost httpPost = new HttpPost(config.getUrl());
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(postParms, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            Log.warn("This systems doesn't support UTF-8!");
        }
        try {
            httpResponse = (BasicHttpResponse) httpClient.execute(httpPost);
        } catch (ClientProtocolException e) {
        //Log.trace("GA connectivity had a problem or the connectivity was aborted.  "+e.toString());
        } catch (IOException e) {
        //Log.trace("GA connectivity suffered a protocol error.  "+e.toString());
        }
        //Log.debug("GA response: " +httpResponse.toString());
        response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
        response.setPostedParms(postParms);
        try {
            EntityUtils.consume(httpResponse.getEntity());
        } catch (IOException e) {
        /*consume quietly*/
        }
        if (config.isGatherStats()) {
            gatherStats(request);
        }
    } catch (Exception e) {
        if (e instanceof UnknownHostException) {
        //Log.trace("Coudln't connect to GA. Internet may not be available. " + e.toString());
        } else {
        //Log.trace("Exception while sending the GA tracker request: " + request +".  "+ e.toString());
        }
    }
    return response;
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpPost(org.apache.http.client.methods.HttpPost) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) UnknownHostException(java.net.UnknownHostException) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 83 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project musiccabinet by hakko.

the class AbstractWSPostClient method executeWSRequest.

/*
	 * Executes a request to a Last.fm web service.
	 * 
	 * When adding support for a new web service, a class extending this should be
	 * implemented. The web service can then be invoked by calling this method, using
	 * relevant parameters.
	 * 
	 * The parameter api_key, which is identical for all web service invocations, is
	 * automatically included.
	 * 
	 * The response is bundled in a WSResponse object, with eventual error code/message.
	 * 
	 * Note: For non US-ASCII characters, Last.fm distinguishes between upper and lower
	 * case. Make sure to use proper capitalization.
	 */
protected WSResponse executeWSRequest(List<NameValuePair> params) throws ApplicationException {
    authenticateParameterList(params);
    WSResponse wsResponse;
    HttpClient httpClient = getHttpClient();
    try {
        HttpPost httpPost = new HttpPost(getURI(params));
        httpPost.setEntity(new UrlEncodedFormEntity(params, CharSet.UTF8));
        HttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        HttpEntity responseEntity = response.getEntity();
        String responseBody = EntityUtils.toString(responseEntity);
        EntityUtils.consume(responseEntity);
        LOG.debug("post responseBody: " + responseBody);
        wsResponse = (statusCode == 200) ? new WSResponse(responseBody) : new WSResponse(isHttpRecoverable(statusCode), statusCode, responseBody);
    } catch (ClientProtocolException e) {
        throw new ApplicationException("The request to post data to Last.fm could not be completed!", e);
    } catch (IOException e) {
        LOG.warn("Could not post data to Last.fm!", e);
        wsResponse = new WSResponse(true, -1, "Call failed due to " + e.getMessage());
    }
    return wsResponse;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ApplicationException(com.github.hakko.musiccabinet.exception.ApplicationException) HttpEntity(org.apache.http.HttpEntity) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 84 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project k-9 by k9mail.

the class WebDavStore method performFormBasedAuthentication.

private void performFormBasedAuthentication(ConnectionInfo info) throws IOException, MessagingException {
    // Clear out cookies from any previous authentication.
    if (authCookies != null) {
        authCookies.clear();
    }
    WebDavHttpClient httpClient = getHttpClient();
    String loginUrl;
    if (info != null) {
        loginUrl = info.guessedAuthUrl;
    } else if (cachedLoginUrl != null && !cachedLoginUrl.equals("")) {
        loginUrl = cachedLoginUrl;
    } else {
        throw new MessagingException("No valid login URL available for form-based authentication.");
    }
    HttpGeneric request = new HttpGeneric(loginUrl);
    request.setMethod("POST");
    // Build the POST data.
    List<BasicNameValuePair> pairs = new ArrayList<>();
    pairs.add(new BasicNameValuePair("destination", baseUrl));
    pairs.add(new BasicNameValuePair("username", username));
    pairs.add(new BasicNameValuePair("password", password));
    pairs.add(new BasicNameValuePair("flags", "0"));
    pairs.add(new BasicNameValuePair("SubmitCreds", "Log+On"));
    pairs.add(new BasicNameValuePair("forcedownlevel", "0"));
    pairs.add(new BasicNameValuePair("trusted", "0"));
    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs);
    request.setEntity(formEntity);
    HttpResponse response = httpClient.executeOverride(request, httpContext);
    boolean authenticated = testAuthenticationResponse(response);
    if (!authenticated) {
        // Check the response from the authentication request above for a form action.
        String formAction = findFormAction(WebDavHttpClient.getUngzippedContent(response.getEntity()));
        if (formAction == null) {
            // If there is no form action, try using our redirect URL from the initial connection.
            if (info != null && info.redirectUrl != null && !info.redirectUrl.equals("")) {
                loginUrl = info.redirectUrl;
                request = new HttpGeneric(loginUrl);
                request.setMethod("GET");
                response = httpClient.executeOverride(request, httpContext);
                formAction = findFormAction(WebDavHttpClient.getUngzippedContent(response.getEntity()));
            }
        }
        if (formAction != null) {
            try {
                URI formActionUri = new URI(formAction);
                URI loginUri = new URI(loginUrl);
                if (formActionUri.isAbsolute()) {
                    // The form action is an absolute URL, just use it.
                    loginUrl = formAction;
                } else {
                    // Append the form action to our current URL, minus the file name.
                    String urlPath;
                    if (formAction.startsWith("/")) {
                        urlPath = formAction;
                    } else {
                        urlPath = loginUri.getPath();
                        int lastPathPos = urlPath.lastIndexOf('/');
                        if (lastPathPos > -1) {
                            urlPath = urlPath.substring(0, lastPathPos + 1);
                            urlPath = urlPath.concat(formAction);
                        }
                    }
                    // Reconstruct the login URL based on the original login URL and the form action.
                    URI finalUri = new URI(loginUri.getScheme(), loginUri.getUserInfo(), loginUri.getHost(), loginUri.getPort(), urlPath, null, null);
                    loginUrl = finalUri.toString();
                }
                // Retry the login using our new URL.
                request = new HttpGeneric(loginUrl);
                request.setMethod("POST");
                request.setEntity(formEntity);
                response = httpClient.executeOverride(request, httpContext);
                authenticated = testAuthenticationResponse(response);
            } catch (URISyntaxException e) {
                Log.e(LOG_TAG, "URISyntaxException caught " + e + "\nTrace: " + WebDavUtils.processException(e));
                throw new MessagingException("URISyntaxException caught", e);
            }
        } else {
            throw new MessagingException("A valid URL for Exchange authentication could not be found.");
        }
    }
    if (authenticated) {
        authenticationType = WebDavConstants.AUTH_TYPE_FORM_BASED;
        cachedLoginUrl = loginUrl;
    } else {
        throw new MessagingException("Invalid credentials provided for authentication.");
    }
}
Also used : MessagingException(com.fsck.k9.mail.MessagingException) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) BasicNameValuePair(org.apache.http.message.BasicNameValuePair)

Example 85 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project UltimateAndroid by cymcsg.

the class HttpUtils_Deprecated method getResponseFromPostUrl.

/*
     * 发送POST请求,通过URL和参数获取服务器反馈应答,通过返回的应答对象 在对数据头进行分析(如获得报文头 报文体等)
     */
public static String getResponseFromPostUrl(String url, String logininfo, List<NameValuePair> params) throws Exception {
    String result = null;
    // 新建HttpPost对象  
    HttpPost httpPost = new HttpPost(url);
    // 设置字符集  
    HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
    // 设置参数实体  
    httpPost.setEntity(entity);
    // 获取HttpClient对象  
    HttpClient httpClient = new DefaultHttpClient();
    //连接超时  
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
    //请求超时  
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
    try {
        // 获取HttpResponse实例  
        HttpResponse httpResp = httpClient.execute(httpPost);
        // 判断是够请求成功  
        if (httpResp.getStatusLine().getStatusCode() == 200) {
            // 获取返回的数据  
            result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
            Logs.d("HttpPost方式请求成功,返回数据如下:");
            Logs.d(result);
        } else {
            Logs.d("HttpPost方式请求失败" + "    " + httpResp.getStatusLine().getStatusCode() + "   " + EntityUtils.toString(httpResp.getEntity(), "UTF-8"));
            result = "connect_failed";
        }
    } catch (ConnectTimeoutException e) {
        result = "over_time";
        Logs.e("HttpPost方式请求失败:  " + "操作超时");
    } catch (Exception e) {
        e.printStackTrace();
        Logs.e(e.getMessage());
        Logs.e(e.getMessage(), "");
        result = "over_time";
    }
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) MalformedURLException(java.net.MalformedURLException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Aggregations

UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)134 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)111 HttpPost (org.apache.http.client.methods.HttpPost)105 NameValuePair (org.apache.http.NameValuePair)100 ArrayList (java.util.ArrayList)96 HttpResponse (org.apache.http.HttpResponse)74 IOException (java.io.IOException)47 HttpEntity (org.apache.http.HttpEntity)40 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)31 ClientProtocolException (org.apache.http.client.ClientProtocolException)27 UnsupportedEncodingException (java.io.UnsupportedEncodingException)26 HttpClient (org.apache.http.client.HttpClient)20 Test (org.junit.Test)20 HttpGet (org.apache.http.client.methods.HttpGet)19 Map (java.util.Map)18 JSONObject (org.json.JSONObject)18 TestHttpClient (io.undertow.testutils.TestHttpClient)14 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)14 HashMap (java.util.HashMap)13 Header (org.apache.http.Header)13