通过 https:// 获取 XML 数据

发布于 2024-12-09 11:21:20 字数 3301 浏览 0 评论 0原文

我的代码适用于 http,但不适用于 https。这是当我在IOException上调用getMessage()时收到的错误消息:

java.net.SocketException:协议不支持地址族

这是我的代码:

 package com.evankimia;

 import java.io.IOException;
 import java.io.StringReader;
 import java.io.UnsupportedEncodingException;
 import java.net.MalformedURLException;

 import org.apache.http.HttpEntity;
 import org.apache.http.HttpResponse;
 import org.apache.http.HttpVersion;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.conn.ClientConnectionManager;
 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.conn.ssl.SSLSocketFactory;
 import org.apache.http.impl.client.DefaultHttpClient;
 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
 import org.apache.http.params.BasicHttpParams;
 import org.apache.http.params.HttpParams;
 import org.apache.http.params.HttpProtocolParams;
 import org.apache.http.protocol.HTTP;
 import org.apache.http.util.EntityUtils;
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
 import org.xmlpull.v1.XmlPullParserFactory;

 import android.app.Activity;
 import android.os.Bundle;
 import android.util.Log;

 public class XMLParserTestActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);       
    {
        Log.e("sys",""+getXML());

     }
 }

    public  String getXML(){
        String line = null;

        try {

            DefaultHttpClient httpClient = this.createHttpClient();
            HttpPost httpPost = new HttpPost("https://web2.uconn.edu/driver/old/timepoints.php?stopid=10");

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            line = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            line = "<results status=\"error\"><msg>Cans't connect to server</msg></results>";
        } catch (MalformedURLException e) {
            line = "<results status=\"error\"><msg>Cand't connect to server</msg></results>";
        } catch (IOException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            e.getMessage();
        }

        return line;

}

private DefaultHttpClient createHttpClient()
{
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);

    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);

    return new DefaultHttpClient(conMgr, params);
}

 }

My code works for http, but not https. Here is the error message im getting when i call getMessage() on the IOException:

java.net.SocketException: Address family not supported by protocol

heres my code:

 package com.evankimia;

 import java.io.IOException;
 import java.io.StringReader;
 import java.io.UnsupportedEncodingException;
 import java.net.MalformedURLException;

 import org.apache.http.HttpEntity;
 import org.apache.http.HttpResponse;
 import org.apache.http.HttpVersion;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.conn.ClientConnectionManager;
 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.conn.ssl.SSLSocketFactory;
 import org.apache.http.impl.client.DefaultHttpClient;
 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
 import org.apache.http.params.BasicHttpParams;
 import org.apache.http.params.HttpParams;
 import org.apache.http.params.HttpProtocolParams;
 import org.apache.http.protocol.HTTP;
 import org.apache.http.util.EntityUtils;
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
 import org.xmlpull.v1.XmlPullParserFactory;

 import android.app.Activity;
 import android.os.Bundle;
 import android.util.Log;

 public class XMLParserTestActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);       
    {
        Log.e("sys",""+getXML());

     }
 }

    public  String getXML(){
        String line = null;

        try {

            DefaultHttpClient httpClient = this.createHttpClient();
            HttpPost httpPost = new HttpPost("https://web2.uconn.edu/driver/old/timepoints.php?stopid=10");

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            line = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            line = "<results status=\"error\"><msg>Cans't connect to server</msg></results>";
        } catch (MalformedURLException e) {
            line = "<results status=\"error\"><msg>Cand't connect to server</msg></results>";
        } catch (IOException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            e.getMessage();
        }

        return line;

}

private DefaultHttpClient createHttpClient()
{
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);

    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);

    return new DefaultHttpClient(conMgr, params);
}

 }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧人 2024-12-16 11:21:20

您列出的方法仅适用于 http。让您的程序识别 https url 并使用如下所示的一些东西。

 /**
 * Initialize the HTTP/S connection (if needed)
 *
 * @param  keystoreFile  the full path of the keystore file
 * @param  keystorePass  the password for the keystore file
 */
private void initHttps(String keystoreFile, String keystorePass)
{
    // check if the URL uses HTTP/S
    if (url.toLowerCase().startsWith(HTTPS_PROTOCOL))
    {
        print("Initializing HTTP/S protocol...");
        // set the system properties needed for HTTP/S
        System.setProperty("javax.net.ssl.keyStore", keystoreFile);
        System.setProperty("javax.net.ssl.keyStorePassword", keystorePass);
        System.setProperty("javax.net.ssl.keyStoreType", "JKS");
        System.setProperty("javax.net.ssl.trustStore", keystoreFile);
        System.setProperty("javax.net.ssl.trustStorePassword", keystorePass);
        System.setProperty("javax.protocol.handler.pkgs",
            "com.sun.net.ssl.internal.www.protocol");
        //int addProvider = Security.addProvider(new       com.sun.net.ssl.internal.ssl.Provider());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
        {   // fix a HTTP/S handshake issue
            public boolean verify(String hostName, SSLSession session)
            {   // Verify that the host name is acceptable 
                return true;
            }
        });
    }
}

The method you listed only works for http. Make your program identify https url and use some thign like following.

 /**
 * Initialize the HTTP/S connection (if needed)
 *
 * @param  keystoreFile  the full path of the keystore file
 * @param  keystorePass  the password for the keystore file
 */
private void initHttps(String keystoreFile, String keystorePass)
{
    // check if the URL uses HTTP/S
    if (url.toLowerCase().startsWith(HTTPS_PROTOCOL))
    {
        print("Initializing HTTP/S protocol...");
        // set the system properties needed for HTTP/S
        System.setProperty("javax.net.ssl.keyStore", keystoreFile);
        System.setProperty("javax.net.ssl.keyStorePassword", keystorePass);
        System.setProperty("javax.net.ssl.keyStoreType", "JKS");
        System.setProperty("javax.net.ssl.trustStore", keystoreFile);
        System.setProperty("javax.net.ssl.trustStorePassword", keystorePass);
        System.setProperty("javax.protocol.handler.pkgs",
            "com.sun.net.ssl.internal.www.protocol");
        //int addProvider = Security.addProvider(new       com.sun.net.ssl.internal.ssl.Provider());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
        {   // fix a HTTP/S handshake issue
            public boolean verify(String hostName, SSLSession session)
            {   // Verify that the host name is acceptable 
                return true;
            }
        });
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文