Search in sources :

Example 31 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project newsrob by marianokamp.

the class GRAnsweredBadRequestException method addParametersIncludingTokenToPostRequest.

private void addParametersIncludingTokenToPostRequest(HttpPost postRequest, List<NameValuePair> nameValuePairs) {
    // add token to the parameters, encode them and put them in the post
    // request
    List<NameValuePair> nvps = new ArrayList<NameValuePair>(nameValuePairs.size() + 1);
    nvps.addAll(nameValuePairs);
    nvps.add(new BasicNameValuePair("T", token));
    try {
        postRequest.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity)

Example 32 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project FastDev4Android by jiangqqlmj.

the class IoUtils method responseFromServiceByPost.

public static String responseFromServiceByPost(String url, String encode, HashMap<String, String> map, RequestCallBack requestCallBack) {
    if (url == null || url.equals("") || map == null) {
        return null;
    }
    if (requestCallBack != null) {
        requestCallBack.onRequestStart();
    }
    Log.d(TAG_LISTLOGIC, "post数据请求地址:" + url);
    if (requestCallBack != null) {
        requestCallBack.onRequestLoading();
    }
    HttpPost httpPost = null;
    URI encodedUri = null;
    try {
        encodedUri = new URI(url);
        httpPost = new HttpPost(encodedUri);
    } catch (URISyntaxException e) {
        // 清理一些空格
        String encodedUrl = url.replace(' ', '+');
        httpPost = new HttpPost(encodedUrl);
        e.printStackTrace();
    }
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEF_CONN_TIMEOUT);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, DEF_SOCKET_TIMEOUT);
    try {
        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey().toString();
            String value = null;
            if (entry.getValue() == null) {
                value = "";
            } else {
                value = entry.getValue().toString();
            }
            Log.d(TAG_LISTLOGIC, "post数据请求参数" + key + "=" + value);
            BasicNameValuePair basicNameValuePair = new BasicNameValuePair(key, value);
            nameValuePair.add(basicNameValuePair);
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, encode));
        // httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair,
        // "GBK"));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        if (httpResponse != null) {
            int code = httpResponse.getStatusLine().getStatusCode();
            if (code == HttpStatus.SC_OK) {
                HttpEntity entity = httpResponse.getEntity();
                String result = EntityUtils.toString(entity).trim();
                Log.d(TAG_LISTLOGIC, "post数据请求服务器返回值200");
                Log.d(TAG_LISTLOGIC, "post返回值:" + result);
                if (requestCallBack != null) {
                    requestCallBack.onRequestSuccess(result);
                }
                return result;
            } else {
                httpPost.abort();
                if (requestCallBack != null) {
                    requestCallBack.onRequestError(RequestCallBack.HTTPSTATUSERROR, "HTTP链接错误");
                }
            }
        } else {
            httpPost.abort();
            if (requestCallBack != null) {
                requestCallBack.onRequestError(RequestCallBack.HTTPRESPONSEERROR, "数据获取异常");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        if (requestCallBack != null) {
            requestCallBack.onRequestError(RequestCallBack.HTTPRESPONSEERROR, "数据获取异常");
        }
        return null;
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        if (requestCallBack != null) {
            requestCallBack.onRequestError(RequestCallBack.OUTOFMEMORYERROR, "内存溢出");
        }
        return null;
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
            httpClient = null;
        }
        if (requestCallBack != null) {
            requestCallBack.onCancel();
        }
    }
    return null;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) URISyntaxException(java.net.URISyntaxException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) URI(java.net.URI) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) URISyntaxException(java.net.URISyntaxException) SocketException(java.net.SocketException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HashMap(java.util.HashMap) Map(java.util.Map)

Example 33 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project ats-framework by Axway.

the class HttpClient method performPostRequest.

/**
     * Perform HTTP POST request based on the host and port specified before
     *
     * @param requestedHostRelativeUrl location/query without host and port like: "/my_dir/res?myParam=1"
     * @param needResponse whether caller needs the contents returned from this request
     * @param paramsMap map of parameters to be sent with this POST request
     * @throws FileTransferException
     */
public String performPostRequest(String requestedHostRelativeUrl, boolean needResponse, HashMap<String, String> paramsMap) throws FileTransferException {
    checkClientInitialized();
    final String getUrl = constructGetUrl(requestedHostRelativeUrl);
    log.info("Performing POST request to: " + getUrl);
    HttpPost postMethod = new HttpPost(getUrl);
    addRequestHeaders(postMethod);
    if (paramsMap != null && paramsMap.size() > 0) {
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(paramsMap.size());
        for (Entry<String, String> paramEntry : paramsMap.entrySet()) {
            log.info("Add parameter " + paramEntry.getKey() + " and value: " + paramEntry.getValue());
            parameters.add(new BasicNameValuePair(paramEntry.getKey(), paramEntry.getValue()));
        }
        UrlEncodedFormEntity sendEntity = null;
        try {
            sendEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            throw new FileTransferException(ex);
        }
        postMethod.setEntity(sendEntity);
    }
    return (String) processHttpRequest(postMethod, needResponse, true);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity)

Example 34 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project intellij-community by JetBrains.

the class EduStepicAuthorizedClient method getTokens.

@Nullable
private static StepicWrappers.TokenInfo getTokens(@NotNull final List<NameValuePair> parameters) {
    final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
    final HttpPost request = new HttpPost(EduStepicNames.TOKEN_URL);
    request.setEntity(new UrlEncodedFormEntity(parameters, Consts.UTF_8));
    try {
        final CloseableHttpClient client = EduStepicClient.getHttpClient();
        final CloseableHttpResponse response = client.execute(request);
        final StatusLine statusLine = response.getStatusLine();
        final HttpEntity responseEntity = response.getEntity();
        final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
        EntityUtils.consume(responseEntity);
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            return gson.fromJson(responseString, StepicWrappers.TokenInfo.class);
        } else {
            LOG.warn("Failed to Login: " + statusLine.getStatusCode() + statusLine.getReasonPhrase());
        }
    } catch (IOException e) {
        LOG.warn(e.getMessage());
    }
    return null;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) GsonBuilder(com.google.gson.GsonBuilder) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Gson(com.google.gson.Gson) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) Nullable(org.jetbrains.annotations.Nullable)

Example 35 with UrlEncodedFormEntity

use of org.apache.http.client.entity.UrlEncodedFormEntity in project DrupalCloud by INsReady.

the class JSONServerClient method systemConnect.

/**
	 * system.connect request for Key Auth
	 */
private void systemConnect() throws ServiceNotAvailableException {
    // Cloud server hand shake
    mPairs.add(new BasicNameValuePair("method", "system.connect"));
    try {
        mSERVER.setEntity(new UrlEncodedFormEntity(mPairs));
        HttpResponse response = mClient.execute(mSERVER);
        InputStream result = response.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(result));
        JSONObject jso = new JSONObject(br.readLine());
        boolean error = jso.getBoolean("#error");
        String data = jso.getString("#data");
        if (error) {
            throw new ServiceNotAvailableException(this, data);
        }
        jso = new JSONObject(data);
        // Save the sessionid to storage
        SharedPreferences auth = mCtx.getSharedPreferences(mPREFS_AUTH, 0);
        SharedPreferences.Editor editor = auth.edit();
        editor.putString("sessionid", jso.getString("sessid"));
        editor.putLong("sessionid_timestamp", new Date().getTime() / 100);
        editor.commit();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) SharedPreferences(android.content.SharedPreferences) InputStream(java.io.InputStream) HttpResponse(org.apache.http.HttpResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONException(org.json.JSONException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) Date(java.util.Date) ClientProtocolException(org.apache.http.client.ClientProtocolException) JSONObject(org.json.JSONObject) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) BufferedReader(java.io.BufferedReader)

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