使用DefaultHttpClient保持活动之间的连接

时间:2012-06-04 18:21:10

标签: android android-activity httpclient keep-alive

我正在开发一个向SAP发送请求的应用程序,当我在应用程序中时,我一直在努力保持连接处于活动状态。

我有三个活动:主要连接列表

当我启动应用程序进入 main 后,点击连接以在SAP和设备之间建立连接并成功连接。

我遇到的问题是,当我按下返回按钮 main 并转到 list 活动时,我无法检索数据,因为我丢失了我的DefaultHttpClient连接。

public String logInToSAP(String PIP, int PPort, String PSchema, String PUser, String PPassword) {
    String result = "";

    //      HttpHost targetHost = new HttpHost(PIP, PPort, PSchema);
    HttpHost targetHost = new HttpHost(PIP, PPort, PSchema);

    //          DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(targetHost.getHostName(), 
            targetHost.getPort()), new UsernamePasswordCredentials(PUser, PPassword));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();

    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // Add AuthCache to the execution context
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_SCHEME_PREF, authCache);

    HttpGet request = new HttpGet("/sap/z_conn");

    ResponseHandler<String> handler = new BasicResponseHandler();
    try {
        result = httpclient.execute(targetHost, request, handler);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        Toast.makeText(this, "Wrong Connection Parameters", Toast.LENGTH_SHORT).show();         
        result = "Wrong Connection Parameters";
    } catch (IOException e) {
        e.printStackTrace();            
        Toast.makeText(this, "IOException", Toast.LENGTH_SHORT).show();
        result = "IOException";
    }
    return result;
}   

1 个答案:

答案 0 :(得分:1)

您可以扩展Application对象并将DefaultHttpClient放在那里。

如何扩展和使用Application对象:

How to declare global variables in Android?