如何在android中使用https url调用webservice

如何在android中使用https url调用webservice,android,Android,我正在尝试使用包含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

我正在尝试使用包含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)

出于开发目的,您需要信任所有证书。使用本教程(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();
        }

    }
}
package com.avilyne.android;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.net.InetAddress;
导入java.net.InetSocketAddress;
导入java.net.Socket;
导入java.net.UnknownHostException;
导入java.security.KeyStore;
导入java.security.KeyStoreException;
导入java.security.NoSuchAlgorithmException;
导入java.security.cert.CertificateException;
导入java.security.cert.x509证书;
导入java.util.ArrayList;
导入javax.net.ssl.SSLContext;
导入javax.net.ssl.SSLSocket;
导入javax.net.ssl.TrustManager;
导入javax.net.ssl.TrustManagerFactory;
导入javax.net.ssl.X509TrustManager;
导入org.apache.http.HttpResponse;
导入org.apache.http.HttpVersion;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.conn.ClientConnectionManager;
导入org.apache.http.conn.ConnectTimeoutException;
导入org.apache.http.conn.params.ConnManagerPNames;
导入org.apache.http.conn.params.connproteBean;
导入org.apache.http.conn.scheme.LayeredSocketFactory;
导入org.apache.http.conn.scheme.PlainSocketFactory;
导入org.apache.http.conn.scheme.scheme;
导入org.apache.http.conn.scheme.SchemeRegistry;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.impl.conn.SingleClientConnManager;
导入org.apache.http.message.BasicNameValuePair;
导入org.apache.http.params.BasicHttpParams;
导入org.apache.http.params.HttpConnectionParams;
导入org.apache.http.params.HttpParams;
导入org.apache.http.params.HttpProtocolParams;
导入org.json.JSONObject;
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.content.Context;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.Menu;
导入android.view.view;
导入android.view.inputmethod.InputMethodManager;
导入android.widget.EditText;
导入android.widget.Toast;
公共类MainActivity扩展了活动{
私有静态最终字符串服务\u URL=
"https://192.168.2.101:8443/RestWebServiceDemo/rest/person";
私有静态最终字符串标记=“AndroidRESTClientActivity”;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
公共无效检索采样数据(视图vw){
字符串sampleURL=SERVICE_URL+“/sample”;
webservicecask wst=新的webservicecask(webservicecask.GET_任务,
“获取数据…”);
execute(新字符串[]{sampleURL});
}
公共控制(查看vw){
EditText edFirstName=(EditText)findViewById(R.id.first\u name);
EditText edLastName=(EditText)findViewById(R.id.last_name);
EditText edEmail=(EditText)findViewById(R.id.email);
edFirstName.setText(“”);
edLastName.setText(“”);
edEmail.setText(“”);
}
公共void postData(查看vw){
EditText edFirstName=(EditText)findViewById(R.id.first\u name);
EditText edLastName=(EditText)findViewById(R.id.last_name);
EditText edEmail=(EditText)findViewById(R.id.email);
字符串firstName=edFirstName.getText().toString();
字符串lastName=edLastName.getText().toString();
字符串email=edEmail.getText().toString();
if(firstName.equals(“”)lastName.equals(“”)email.equals(“”){
Toast.makeText(这是“请在所有必填字段中输入”,
Toast.LENGTH_LONG).show();
回来
}
WebServiceTask wst=新的WebServiceTask(WebServiceTask.POST_任务,此,
“发布数据…”);
wst.addNameValuePair(“firstName”,firstName);
wst.addNameValuePair(“lastName”,lastName);
wst.addNameValuePair(“电子邮件”,电子邮件);
//传递的字符串是我们将发布到的URL
execute(新字符串[]{SERVICE_URL});
}
公共无效句柄响应(字符串响应){
EditText edFirstName=(EditText)findViewById(R.id.first\u name);
EditText edLastName=(EditText)findViewById(R.id.last_name);
EditText edEmail=(EditText)findViewById(R.id.email);
edFirstName.setText(“”);
edLastName.setText(“”);
edEmail.setText(“”);
试一试{
JSONObject jso=新的JSONObject(响应);
String firstName=jso.getString(“firstName”);
String lastName=jso.getString(“lastName”);
String email=jso.getString(“email”);
edFirstName.setText(firstName);
edLastName.setText(lastName);
edEmail.setText(电子邮件);
}捕获(例外e){
Log.e(TAG,e.getLocalizedMessage(),e);
}
}
私有void隐藏板(){
InputMethodManager inputManager=(InputMethodManager)MainActivity.this
.getSystemService(Context.INPUT\u方法\u服务);
inputManager.hideSoftInputFromWindow(MainActivity.this
.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE(不总是);
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
getMenuInflater().充气(R.menu.activity\u主菜单);
返回true;
}
私有类WebServiceTask扩展异步任务{
公共静态最终int POST_任务=1;
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();
        }

    }
}
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;

}

}