1

我正在尝试使用包含 HTTPS 的 URL 访问 Web 服务我收到没有对等证书错误。以下是我得到的错误。谁能帮帮我吗?

08-04 12:17:52.351: I/ApplicationPackageManager(8068): cscCountry is not German : INS
08-04 12:17:52.875: D/dalvikvm(8068): GC_EXTERNAL_ALLOC freed 60K, 48% free 2801K/5379K, external 504K/517K, paused 47ms
08-04 12:18:08.453: W/KeyCharacterMap(8068): Can't open keycharmap file
08-04 12:18:08.453: W/KeyCharacterMap(8068): Error loading keycharmap file '/system/usr/keychars/sec_keypad.kcm.bin'. hw.keyboards.0.devname='sec_keypad'
08-04 12:18:08.453: W/KeyCharacterMap(8068): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
08-04 12:18:17.656: D/dalvikvm(8068): GC_CONCURRENT freed 198K, 47% free 3005K/5639K, external 617K/1023K, paused 4ms+4ms
08-04 12:18:17.695: W/System.err(8068): javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
08-04 12:18:17.718: W/System.err(8068):     at org.apache.harmony.xnet.provider.jsse.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:258)
08-04 12:18:17.718: W/System.err(8068):     at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:93)
08-04 12:18:17.718: W/System.err(8068):     at org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:381)
08-04 12:18:17.718: W/System.err(8068):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:164)
08-04 12:18:17.718: W/System.err(8068):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-04 12:18:17.718: W/System.err(8068):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-04 12:18:17.718: W/System.err(8068):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
08-04 12:18:17.718: W/System.err(8068):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-04 12:18:17.718: W/System.err(8068):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-04 12:18:17.718: W/System.err(8068):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-04 12:18:17.718: W/System.err(8068):     at com.osi.wolla.login.Login$task.doInBackground(Login.java:223)
08-04 12:18:17.718: W/System.err(8068):     at com.osi.wolla.login.Login$task.doInBackground(Login.java:1)
08-04 12:18:17.718: W/System.err(8068):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
08-04 12:18:17.718: W/System.err(8068):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
08-04 12:18:17.718: W/System.err(8068):     at java.util.concurrent.FutureTask.run(FutureTask.java:138)
08-04 12:18:17.718: W/System.err(8068):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
08-04 12:18:17.718: W/System.err(8068):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
08-04 12:18:17.718: W/System.err(8068):     at java.lang.Thread.run(Thread.java:1019)
08-04 12:18:17.718: I/System.out(8068): response....null
08-04 12:18:17.757: I/System.out(8068): url....https://mywolla.com/mobwebservices/smails_rest.php
08-04 12:18:21.687: W/webserviceCall(8068): Error for URL https://mywolla.com/mobwebservices/smails_rest.php
08-04 12:18:21.687: W/webserviceCall(8068): javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.harmony.xnet.provider.jsse.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:258)
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:93)
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:381)
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:164)
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-04 12:18:21.687: W/webserviceCall(8068):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-04 12:18:21.687: W/webserviceCall(8068):     at com.osi.wolla.webserviceCall.getBundle(webserviceCall.java:870)
08-04 12:18:21.687: W/webserviceCall(8068):     at com.osi.wolla.login.Login$task.onPostExecute(Login.java:165)
08-04 12:18:21.687: W/webserviceCall(8068):     at com.osi.wolla.login.Login$task.onPostExecute(Login.java:1)
08-04 12:18:21.687: W/webserviceCall(8068):     at android.os.AsyncTask.finish(AsyncTask.java:417)
08-04 12:18:21.687: W/webserviceCall(8068):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
08-04 12:18:21.687: W/webserviceCall(8068):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
08-04 12:18:21.687: W/webserviceCall(8068):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-04 12:18:21.687: W/webserviceCall(8068):     at android.os.Looper.loop(Looper.java:130)
08-04 12:18:21.687: W/webserviceCall(8068):     at android.app.ActivityThread.main(ActivityThread.java:3687)
08-04 12:18:21.687: W/webserviceCall(8068):     at java.lang.reflect.Method.invokeNative(Native Method)
08-04 12:18:21.687: W/webserviceCall(8068):     at java.lang.reflect.Method.invoke(Method.java:507)
08-04 12:18:21.687: W/webserviceCall(8068):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
08-04 12:18:21.687: W/webserviceCall(8068):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-04 12:18:21.687: W/webserviceCall(8068):     at dalvik.system.NativeStart.main(Native Method)
08-04 12:18:21.695: D/AndroidRuntime(8068): Shutting down VM
08-04 12:18:21.695: W/dalvikvm(8068): threadid=1: thread exiting with uncaught exception (group=0x40018578)
08-04 12:18:21.695: E/AndroidRuntime(8068): FATAL EXCEPTION: main
08-04 12:18:21.695: E/AndroidRuntime(8068): java.lang.NullPointerException
08-04 12:18:21.695: E/AndroidRuntime(8068):     at java.io.StringReader.<init>(StringReader.java:46)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at com.osi.wolla.xmlParser.parseUser(xmlParser.java:239)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at com.osi.wolla.login.Login$task.onPostExecute(Login.java:168)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at com.osi.wolla.login.Login$task.onPostExecute(Login.java:1)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at android.os.AsyncTask.finish(AsyncTask.java:417)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at android.os.Looper.loop(Looper.java:130)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at android.app.ActivityThread.main(ActivityThread.java:3687)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at java.lang.reflect.Method.invokeNative(Native Method)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at java.lang.reflect.Method.invoke(Method.java:507)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-04 12:18:21.695: E/AndroidRuntime(8068):     at dalvik.system.NativeStart.main(Native Method)


这是我的代码。

   final String URL = "https://mywolla.com/mobwebservices/svalidateuser.php?wsdl";

   String response = null;
            try {

                 HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

                   DefaultHttpClient client = new DefaultHttpClient();

                   SchemeRegistry registry = new SchemeRegistry();
                   SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
                   socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
                   registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
                   registry.register(new Scheme("https", socketFactory, 443));
                   SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
                   DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

                   // Set verifier      
                   HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

                   // Example send http request

                   HttpPost httpPost = new HttpPost(URL);

                   HttpResponse response1 = httpClient.execute(httpPost);
4

2 回答 2

4

出于开发目的,您需要信任所有证书。使用本教程 (avilyne.com/?p=105)

将密钥库文件添加到 res/raw 目录。并将主要活动代码替换为以下内容。

package com.avilyne.android;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnManagerPNames;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.LayeredSocketFactory;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private static final String SERVICE_URL =
    "https://192.168.2.101:8443/RestWebServiceDemo/rest/person";

    private static final String TAG = "AndroidRESTClientActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void retrieveSampleData(View vw) {

        String sampleURL = SERVICE_URL + "/sample";

        WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK, this,
                "GETting data...");

        wst.execute(new String[] { sampleURL });

    }

    public void clearControls(View vw) {

        EditText edFirstName = (EditText) findViewById(R.id.first_name);
        EditText edLastName = (EditText) findViewById(R.id.last_name);
        EditText edEmail = (EditText) findViewById(R.id.email);

        edFirstName.setText("");
        edLastName.setText("");
        edEmail.setText("");

    }

    public void postData(View vw) {

        EditText edFirstName = (EditText) findViewById(R.id.first_name);
        EditText edLastName = (EditText) findViewById(R.id.last_name);
        EditText edEmail = (EditText) findViewById(R.id.email);

        String firstName = edFirstName.getText().toString();
        String lastName = edLastName.getText().toString();
        String email = edEmail.getText().toString();

        if (firstName.equals("") || lastName.equals("") || email.equals("")) {
            Toast.makeText(this, "Please enter in all required fields.",
                    Toast.LENGTH_LONG).show();
            return;
        }

        WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this,
                "Posting data...");

        wst.addNameValuePair("firstName", firstName);
        wst.addNameValuePair("lastName", lastName);
        wst.addNameValuePair("email", email);

        // the passed String is the URL we will POST to
        wst.execute(new String[] { SERVICE_URL });

    }

    public void handleResponse(String response) {

        EditText edFirstName = (EditText) findViewById(R.id.first_name);
        EditText edLastName = (EditText) findViewById(R.id.last_name);
        EditText edEmail = (EditText) findViewById(R.id.email);

        edFirstName.setText("");
        edLastName.setText("");
        edEmail.setText("");

        try {

            JSONObject jso = new JSONObject(response);

            String firstName = jso.getString("firstName");
            String lastName = jso.getString("lastName");
            String email = jso.getString("email");

            edFirstName.setText(firstName);
            edLastName.setText(lastName);
            edEmail.setText(email);

        } catch (Exception e) {
            Log.e(TAG, e.getLocalizedMessage(), e);
        }

    }

    private void hideKeyboard() {

        InputMethodManager inputManager = (InputMethodManager) MainActivity.this
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        inputManager.hideSoftInputFromWindow(MainActivity.this
                .getCurrentFocus().getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    private class WebServiceTask extends AsyncTask<String, Integer, String> {

        public static final int POST_TASK = 1;
        public static final int GET_TASK = 2;

        private static final String TAG = "WebServiceTask";

        // connection timeout, in milliseconds (waiting to connect)
        // private static final int CONN_TIMEOUT = 3000;

        // socket timeout, in milliseconds (waiting for data)
        // private static final int SOCKET_TIMEOUT = 5000;

        private int taskType = GET_TASK;
        private Context mContext = null;
        private String processMessage = "Processing...";

        private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

        private ProgressDialog pDlg = null;

        public WebServiceTask(int taskType, Context mContext,
                String processMessage) {

            this.taskType = taskType;
            this.mContext = mContext;
            this.processMessage = processMessage;
        }

        public void addNameValuePair(String name, String value) {

            params.add(new BasicNameValuePair(name, value));
        }

        private void showProgressDialog() {

            pDlg = new ProgressDialog(mContext);
            pDlg.setMessage(processMessage);
            pDlg.setProgressDrawable(mContext.getWallpaper());
            pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDlg.setCancelable(false);
            pDlg.show();

        }

        @Override
        protected void onPreExecute() {

            hideKeyboard();
            showProgressDialog();

        }

        protected String doInBackground(String... urls) {

            String url = urls[0];
            String result = "";

            HttpResponse response = doResponse(url);

            if (response == null) {
                return result;
            } else {

                try {

                    result = inputStreamToString(response.getEntity()
                            .getContent());

                } catch (IllegalStateException e) {
                    Log.e(TAG, e.getLocalizedMessage(), e);

                } catch (IOException e) {
                    Log.e(TAG, e.getLocalizedMessage(), e);
                }

            }

            return result;
        }

        @Override
        protected void onPostExecute(String response) {

            handleResponse(response);
            pDlg.dismiss();

        }

        // Establish connection and socket (data retrieval) timeouts
        /*
         * private HttpParams getHttpParams() {
         * 
         * HttpParams htpp = new BasicHttpParams();
         * 
         * HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
         * HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
         * 
         * return htpp; }
         */

        private HttpResponse doResponse(String url) {

            // Use our connection and data timeouts as parameters for our
            // DefaultHttpClient
            // HttpClient httpclient = new DefaultHttpClient(getHttpParams());

            DefaultHttpClient httpsclient = httpsClient();

            HttpResponse response = null;

            try {
                switch (taskType) {

                case POST_TASK:
                    HttpPost httppost = new HttpPost(url);
                    // Add parameters
                    httppost.setEntity(new UrlEncodedFormEntity(params));

                    response = httpsclient.execute(httppost); // httpclient.execute(httppost);
                    break;
                case GET_TASK:
                    HttpGet httpget = new HttpGet(url);
                    response = httpsclient.execute(httpget); // httpclient.execute(httpget);
                    break;
                }
            } catch (Exception e) {

                Log.e(TAG, e.getLocalizedMessage(), e);

            }

            return response;
        }

        private String inputStreamToString(InputStream is) {

            String line = "";
            StringBuilder total = new StringBuilder();

            // Wrap a BufferedReader around the InputStream
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            try {
                // Read response until the end
                while ((line = rd.readLine()) != null) {
                    total.append(line);
                }
            } catch (IOException e) {
                Log.e(TAG, e.getLocalizedMessage(), e);
            }

            // Return full string
            return total.toString();
        }

    }

    private DefaultHttpClient httpsClient() {
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory
                .getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(),
                443));

        HttpParams httpParams = new BasicHttpParams();
        httpParams.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        httpParams.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE,
                new ConnPerRouteBean(30));
        httpParams.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

        ClientConnectionManager cm = new SingleClientConnManager(httpParams,
                schemeRegistry);
        return new DefaultHttpClient(cm, httpParams);
    }

    private class EasySSLSocketFactory implements LayeredSocketFactory {
        private SSLContext sslcontext = null;

        private SSLContext createEasySSLContext() throws IOException {
            try {
                SSLContext context = SSLContext.getInstance("TLS");
                context.init(null,
                        new TrustManager[] { new EasyX509TrustManager(null) },
                        null);
                return context;
            } catch (Exception e) {
                throw new IOException(e.getMessage());
            }
        }

        private SSLContext getSSLContext() throws IOException {
            if (this.sslcontext == null) {
                this.sslcontext = createEasySSLContext();
            }
            return this.sslcontext;
        }

        /**
         * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,
         *      java.lang.String, int, java.net.InetAddress, int,
         *      org.apache.http.params.HttpParams)
         */
        public Socket connectSocket(Socket sock, String host, int port,
                InetAddress localAddress, int localPort, HttpParams params)
                throws IOException, UnknownHostException,
                ConnectTimeoutException {
            int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
            int soTimeout = HttpConnectionParams.getSoTimeout(params);

            InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
            SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock
                    : createSocket());

            if ((localAddress != null) || (localPort > 0)) {
                // we need to bind explicitly
                if (localPort < 0) {
                    localPort = 0; // indicates "any"
                }
                InetSocketAddress isa = new InetSocketAddress(localAddress,
                        localPort);
                sslsock.bind(isa);
            }

            sslsock.connect(remoteAddress, connTimeout);
            sslsock.setSoTimeout(soTimeout);
            return sslsock;

        }

        /**
         * @see org.apache.http.conn.scheme.SocketFactory#createSocket()
         */
        public Socket createSocket() throws IOException {
            return getSSLContext().getSocketFactory().createSocket();
        }

        /**
         * @see org.apache.http.conn.scheme.SocketFactory#isSecure(java.net.Socket)
         */
        public boolean isSecure(Socket socket) throws IllegalArgumentException {
            return true;
        }

        /**
         * @see org.apache.http.conn.scheme.LayeredSocketFactory#createSocket(java.net.Socket,
         *      java.lang.String, int, boolean)
         */
        public Socket createSocket(Socket socket, String host, int port,
                boolean autoClose) throws IOException, UnknownHostException {
            // return getSSLContext().getSocketFactory().createSocket(socket,
            // host, port, autoClose);
            return getSSLContext().getSocketFactory().createSocket(socket,
                    host, port, autoClose);
        }

        // -------------------------------------------------------------------
        // javadoc in org.apache.http.conn.scheme.SocketFactory says :
        // Both Object.equals() and Object.hashCode() must be overridden
        // for the correct operation of some connection managers
        // -------------------------------------------------------------------

        public boolean equals(Object obj) {
            return ((obj != null) && obj.getClass().equals(
                    EasySSLSocketFactory.class));
        }

        public int hashCode() {
            return EasySSLSocketFactory.class.hashCode();
        }

    }

    private class EasyX509TrustManager implements X509TrustManager {
        private X509TrustManager standardTrustManager = null;

        /**
         * Constructor for EasyX509TrustManager.
         */
        public EasyX509TrustManager(KeyStore keystore)
                throws NoSuchAlgorithmException, KeyStoreException {
            super();
            TrustManagerFactory factory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            factory.init(keystore);
            TrustManager[] trustmanagers = factory.getTrustManagers();
            if (trustmanagers.length == 0) {
                throw new NoSuchAlgorithmException("no trust manager found");
            }
            this.standardTrustManager = (X509TrustManager) trustmanagers[0];
        }

        /**
         * @see 
         *      javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate
         *      [],String authType)
         */
        public void checkClientTrusted(X509Certificate[] certificates,
                String authType) throws CertificateException {
            standardTrustManager.checkClientTrusted(certificates, authType);
        }

        /**
         * @see 
         *      javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate
         *      [],String authType)
         */
        public void checkServerTrusted(X509Certificate[] certificates,
                String authType) throws CertificateException {
            if ((certificates != null) && (certificates.length == 1)) {
                certificates[0].checkValidity();
            } else {
                standardTrustManager.checkServerTrusted(certificates, authType);
            }
        }

        /**
         * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
         */
        public X509Certificate[] getAcceptedIssuers() {
            return this.standardTrustManager.getAcceptedIssuers();
        }

    }
}
于 2012-08-04T07:02:39.173 回答
1

请使用以下代码:

public class WebAPIRequest {


public static String convertStreamToString(InputStream is)
        throws IOException {
    if (is != null) {
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(is, "UTF-8"));
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } finally {
            is.close();
        }
        return sb.toString();
    } else {
        return "";
    }
}

public static Document performPost(String url, String body) {
    Document doc = null;

    try {
        HttpParams basicparams = new BasicHttpParams();
        URI uri = new URI(url);
        HttpPost method = new HttpPost(uri);
        int timeoutConnection = 60000;
        HttpConnectionParams.setConnectionTimeout(basicparams,
                timeoutConnection);
        DefaultHttpClient client = new DefaultHttpClient(basicparams);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        body = body.replaceAll("%20", " ");
        String[] parameters = body.split("&");
        for (int i = 0; i < parameters.length; i++) {
            String[] parameter = parameters[i].split("=");
            if (parameter.length >= 2) {
                nameValuePairs.add(new BasicNameValuePair(parameter[0],
                        parameter[1]));
            }
        }
        method.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse res = client.execute(method);

        InputStream data = res.getEntity().getContent();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        doc = db.parse(data);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        // e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        // e.printStackTrace();
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return doc;
}

public static String performRequestAsString(String url, String method,
        List<NameValuePair> params) {
    String value = null;

    try {

        if (method == "POST") {
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            String paramString = URLEncodedUtils.format(params, "utf-8");
            String sampleurl = url + "" + paramString;
            Log.e("Request_Url", "" + sampleurl);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream is = httpEntity.getContent();
            value = convertStreamToString(is);

        } else if (method == "GET") {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "" + paramString;
            Log.e("Request_Url", "" + url);
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream is = httpEntity.getContent();
            value = convertStreamToString(is);
        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        // e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return value;
}

public static JSONObject makeJsonObjHttpRequest(String url, String method,
        List<NameValuePair> params) {

    InputStream is = null;
    JSONObject jObj = null;
    String json = "";
    // Making HTTP request
    try {

        // check for request method
        if (method == "POST") {
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            String paramString = URLEncodedUtils.format(params, "utf-8");
            String sampleurl = url + "" + paramString;
            Log.e("Request_Url", "" + sampleurl);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } else if (method == "GET") {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "" + paramString;
            Log.e("Request_Url", "" + url);
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

public static JSONArray makeJsonArryHttpRequest(String url, String method,
        List<NameValuePair> params) {

    InputStream is = null;
    JSONArray jArray = null;
    String json = "";
    // Making HTTP request
    try {

        // check for request method
        if (method == "POST") {
            // request method is POST
            // defaultHttpClient

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            String paramString = URLEncodedUtils.format(params, "utf-8");
            String sampleurl = url + "" + paramString;
            Log.e("Request_Url", "" + sampleurl);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } else if (method == "GET") {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "" + paramString;
            Log.e("Request_Url", "" + url);
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jArray = new JSONArray(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jArray;

}

}
于 2013-09-13T09:14:38.940 回答