2

我刚刚开始在 android 中编程,我正在使用代码从 https 加密服务器检索 xml 文件。

public String getXmlFromUrl(String url) {
    String xml = null;

    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
    xml = EntityUtils.toString(httpEntity);
    Log.w(TAG,"xml recieved");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // return XML
    return xml;
}

我读过一些文章,告诉我关于SSLScoketFactory信任经理和所有的事情。它非常混乱。谁能告诉我现在应该做什么或如何进行?我不担心中间人攻击。我只需要检索 xml 文件。

谢谢。

4

1 回答 1

2

您可以通过以下方式执行此操作......

1.如果您访问的站点没有经过认证,那么您需要创建一个自定义证书。

2.然后你需要将xml作为String传递给Server。

例如:

自定义证书类,带有返回 HttpClient 对象的方法

public class MySSLSocketFactory extends SSLSocketFactory {
    SSLContext sslContext = SSLContext.getInstance("TLS");

    public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(truststore);

        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sslContext.init(null, new TrustManager[] { tm }, null);
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }


public static HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

}

将 xml 发布到服务器的代码:

public String postData(String url, String xmlQuery) {



        final String urlStr = url;
        final String xmlStr = xmlQuery;
        final StringBuilder sb  = new StringBuilder();



        Thread t1 = new Thread(new Runnable() {

            public void run() {

                HttpClient httpclient = MySSLSocketFactory.getNewHttpClient();

                HttpPost httppost = new HttpPost(urlStr);


try {

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);

    Log.d("Vivek", response.toString());

                    HttpEntity entity = response.getEntity();
                    InputStream i = entity.getContent();

                    Log.d("Vivek", i.toString());
                    InputStreamReader isr = new InputStreamReader(i);

                    BufferedReader br = new BufferedReader(isr);

                    String s = null;


                    while ((s = br.readLine()) != null) {

                        Log.d("YumZing", s);
                        sb.append(s);
                    }


                    Log.d("Check Now",sb+"");




                } catch (ClientProtocolException e) {

                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } /*
                 * catch (ParserConfigurationException e) { // TODO
                 * Auto-generated catch block e.printStackTrace(); } catch
                 * (SAXException e) { // TODO Auto-generated catch block
                 * e.printStackTrace(); }
                 */
            }

        });

        t1.start();
        try {
            t1.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        System.out.println("Getting from Post Data Method "+sb.toString());

        return sb.toString();
    }
于 2012-07-02T12:14:52.840 回答