how to make HTTPS calls using AsyncHttpClient?

青春壹個敷衍的年華 提交于 2019-11-28 06:06:43

You need import the public server certificate into your default keystore, or if you are not interested in the authentication of your client you can initialize the AsyncHttpClient with

AsyncHttpClient asycnHttpClient = new AsyncHttpClient(true, 80, 443);

but this trick is not secure because use a custom SSLSocketFactory implementation whos omit the SSL certificate validation, take a look at the AsyncHttpClient source code.

More information about SSLSocketFactory at https://developer.android.com/reference/org/apache/http/conn/ssl/SSLSocketFactory.html

you can also solve this problem, with adding this 1 line.

asyncHttpClient.setSSLSocketFactory(MySSLSocketFactory.getFixedSocketFactory());

I have a simple http client that calls https service:

import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

/**
 */
public class HttpSimpleClient {

    private static final String TAG = HttpSimpleClient.class.getSimpleName();

    private static HttpSimpleClient instance;

    private HttpSimpleClient(){}

    public static HttpSimpleClient instance(){
        if (instance==null) {
            instance = new HttpSimpleClient();
        }
        return instance;
    }

    public <T> T post(URL url,
                      List<NameValuePair> header,
                      List<NameValuePair> parameter,
                      ResponseHandler<T> responseHandler) throws IOException {
        return post(url, header, parameter, responseHandler, null, null);
    }

    public <T> T post(URL url,
                     List<NameValuePair> header,
                     List<NameValuePair> parameter,
                     ResponseHandler<T> responseHandler,
                     AuthScope proxy,
                     UsernamePasswordCredentials proxyUser) throws IOException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost request = new HttpPost(url.toString());

        if (header!=null) {
            for (NameValuePair head : header){
                request.setHeader(head.getName(), head.getValue());
            }
            Log.d(TAG, "Aggiunti header: "+ header.size());

        } else {
            // Header di default
            request.setHeader("Content-Type", "application/x-www-form-urlencoded");
            request.setHeader("User-Agent", System.getProperty("http.agent"));
            Log.d(TAG, "Aggiunti header di defautl");
        }

        if (parameter!=null) {
            request.setEntity(new UrlEncodedFormEntity(parameter, HTTP.UTF_8));
            Log.d(TAG, "Aggiunti parametri: "+ parameter.size());
        }


        if (proxy!=null) {
            if (proxyUser!=null) {
                ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(proxy, proxyUser);

            } else {
                // TODO gestire proxy senza credenziali
                ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(proxy, null);

            }
            Log.d(TAG, "Impostato Proxy per la connessione");
        }
        return httpClient.execute(request, responseHandler);
    }


    public static String httpResponseToString(HttpResponse httpResponse, int bufferSize) throws IOException {
        InputStream content = httpResponse.getEntity().getContent();

        int numRead;
        byte[] buffer = new byte[bufferSize];
        ByteArrayOutputStream outString = new ByteArrayOutputStream();
        try{
            while ((numRead = content.read(buffer)) != -1) {
                outString.write(buffer, 0, numRead);
            }
        } finally {
            content.close();
        }
        return new String(outString.toByteArray());
    }
}

And i use it in a AsyncTask:

response = HttpSimpleClient.instance().post(
                    getServiceURL(), // HTTPS url
                    mHeader, // List<NameValuePair>
                    mParameter, // List<NameValuePair>
                    getResponseHandler() // org.apache.http.client.ResponseHandler
            );

Tested on Android api>=10

Rajesh Kumar

Here is my code:

private Map<String, String> mParams;

public void sendata(View v) throws JSONException {
    username = (EditText) findViewById(R.id.txtusername);
    password = (EditText) findViewById(R.id.txtpassword);

    final ProgressDialog pDialog = new ProgressDialog(this);
    pDialog.setMessage("Loading...");
    pDialog.show();
    JSONObject j = new JSONObject();
    j.put("password", password.getText());
    j.put("username", username.getText());
    j.put("Deviceid", 123456789);
    j.put("RoleId", 1);
    String url = Url;
    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams params = new RequestParams();
    params.put("json", j.toString());
    client.post(url, params, new JsonHttpResponseHandler() {
        @SuppressLint("NewApi")
        public void onSuccess(JSONObject response) {
            pDialog.hide();
            JSONObject jsnObjct;
            try {
                JSONObject json = (JSONObject) new JSONTokener(response
                        .toString()).nextValue();
                JSONObject json2 = json.getJSONObject("Data");
                JSONArray test = (JSONArray) json2
                        .getJSONArray("PatientAllergies");
                for (int i = 0; i < test.length(); i++) {
                    json = test.getJSONObject(i);
                    System.out.print(json.getString("PatientId"));
                    System.out.print(json.getString("Id"));
                    System.out.print(json.getString("AllergyName"));
                    System.out.print(json.getString("Reaction"));
                    System.out.print(json.getString("OnSetDate"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        public void onFailure(int statusCode, Header[] headers, String res,
                Throwable t) {
            pDialog.hide();
        }
    });

}
JSONObject jsonObject;

private void parsejson(JSONObject response) {

    try {
        jsonObject = response;
        System.out.print(response.toString());
        JSONObject jsnObjct = jsonObject.getJSONObject("Data");
        System.out.print(jsonObject.toString());
        jsnObjct = jsnObjct.getJSONObject("PhysicianDetail");

        System.out.print(jsnObjct.toString());

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!