Can't get HttpParams working with Postrequest

后端 未结 2 1208
清歌不尽
清歌不尽 2021-01-04 05:12

I can\'t get the HttpParams-stuff from the Android-API working.

I just wan\'t to send some simple Parameters with my Postrequest. Everything is working fine, except

2条回答
  •  我在风中等你
    2021-01-04 05:27

    Tried to get it work the first way, but it seems HttpParams interface isn't intended to be built for that. Having Googled for a while, I found this SO answer explaining it:

    The HttpParams interface isn't there for specifying query string parameters, it's for specifying runtime behaviour of the HttpClient object.

    The documentation isn't so specific, though:

    HttpParams interface represents a collection of immutable values that define a runtime behavior of a component.

    For setting connection and request timeouts, I've used a mix of both HttpParams and List, which is fully functional and uses the AndroidHttpClient class, available from API 8:

    public HttpResponse securityCheck(String loginUrl, String name, String password) {
        AndroidHttpClient client = AndroidHttpClient.newInstance(null);
        HttpPost requestLogin = new HttpPost(
                loginUrl + "?");
    
        //Set my own params using NamaValuePairs
        List params = new ArrayList();
        params.add(new BasicNameValuePair("j_username", name));
        params.add(new BasicNameValuePair("j_password", password));
    
        //Set the timeouts using the wrapped HttpParams
        HttpParams httpParameters = client.getParams();
        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        try {
            requestLogin
                    .setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse response = client.execute(requestLogin);
            return response;
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
            return null;
        }finally {
            client.close();
        }
    }
    

    See also:

    • How to set HttpResponse timeout for Android in Java

提交回复
热议问题