0

通话后activityForResult三星 Galaxy S3 丢失了 cookie 存储,该存储存储为 Application 类的静态字段。我想知道为什么会这样。

注意三星 Galaxy Tab 7.7 和 HTC Rhyme/Desire 从未出现此错误。

我调用 JSONParser.getJsonFromUrl,我想在其中执行网络操作。
getJsonFromUrl 向 httpClient 询问 UILapplication,它由 HttpClientFactory 提供。Meanwile UILApplications 将 cookie strore 恢复到客户端。我相信它应该减少互联网下降。

public class UILApplication extends Application {
private static CookieStore mCookie = null;
public static DefaultHttpClient client;
private static DefaultHttpClient httpClient;
    public static HttpClient getHttpClient() {
         httpClient = HttpClientFactory
                .getThreadSafeClient();
        synchronized (mLock) {

            if (mCookie == null) {
                mCookie = httpClient.getCookieStore();
            } else {
                httpClient.setCookieStore(mCookie);
            }

        }
        List<Cookie> cookies = mCookie.getCookies();
        if (cookies.isEmpty()) {
            Log.d("COOK", "request - none");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                Log.d("COOK", "request - " + cookies.get(i).toString());
            }
        }
        return httpClient;
    }
}

Json 解析器 - 执行网络操作的类

public class JSONParser {
static Context context;
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        HttpResponse httpResponse = null;
        InputStream is = null;
        JSONObject jObj = null;
        String json = "";
        HttpClient httpClient = null;
        if (isOnline()) {
            try {

                String u = url;
                u = u + "?";
                httpClient = UILApplication.getHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                for (int i = 0; i < params.size(); i++) {
                    u = u + params.get(i).getName() + "="
                            + params.get(i).getValue() + "&";
                }
                Log.d("URL", u);
                httpResponse = httpClient.execute(httpPost);
                List<Cookie> cookies = ((AbstractHttpClient) httpClient)
                        .getCookieStore().getCookies();
                if (cookies.isEmpty()) {
                    Log.d("COOK", "response - none");
                } else {
                    for (int i = 0; i < cookies.size(); i++) {
                        Log.d("COOK", "response - " + cookies.get(i).toString());
                    }
                }
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
                Log.d("data is sent", "true");

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

            }
            Log.d("wait", "true");
            try {

                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is, "UTF-8"), 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());
                return null;
            }
            // 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 null;
            }
            if (json.contains("error\":2")) {
                Log.e("JSON",  jObj.toString());

                HttpClientFactory.killSession();
                UILApplication.login = 2;
                return null;
            }
            if (jObj != null) {
                Log.d("JSON", jObj.toString());
            } 

            return jObj;
        }
        return null;

    }
}

HttpClientFactory

public class HttpClientFactory {
    private static DefaultHttpClient client = null;



    public synchronized static DefaultHttpClient getThreadSafeClient() {

        if (client != null) {
            Log.d("HTTPCLIEN", "REUSE");

            // return client;
        } else {
            Log.d("HTTPCLIEN", "new");
            client = new DefaultHttpClient();

            client.getConnectionManager();

            HttpParams params = client.getParams();
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
            HttpProtocolParams.setHttpElementCharset(params, HTTP.UTF_8);
            SchemeRegistry schReg = new SchemeRegistry();
            schReg.register(new Scheme("http", PlainSocketFactory
                    .getSocketFactory(), 80));
            ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
                    params, schReg);

            client = new DefaultHttpClient(conMgr, params);

            // return client;
        }
        // synchronized (mLock) {

        return client;
    }


}
4

1 回答 1

0

这个修复看起来很可靠

保存 cookie 的 Idia 不是在静态单例中,而是在 savedInstance 中。

public class SerializedCookie implements Serializable {

    private static final long serialVersionUID = 5327445113190674523L; //arbitrary

    private String name;
    private String value;
    private String domain;

    public SerializedCookie(Cookie cookie){
        this.name = cookie.getName();
        this.value = cookie.getValue();
        this.domain = cookie.getDomain();
    }

    public String getName(){
        return name;
    }

    public String getValue(){
        return value;
    }
    public String getDomain(){
        return domain;
    }
}
  protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        List<Cookie> cookies =client.getCookies();
        if (!cookies.isEmpty()){
            Cookie sessionInfo = cookies.get(0);
            outState.putSerializable("sessionInfo", new SerializedCookie(sessionInfo));
        }
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       if (client.getCookies().isEmpty()){
           if (savedInstanceState.containsKey("sessionInfo")){
               SerializedCookie cookie = (SerializedCookie) savedInstanceState.
                   getSerializable("sessionInfo");

               BasicClientCookie newCookie = new BasicClientCookie(cookie.getName(),
                       cookie.getValue());
                       newCookie.setDomain(cookie.getDomain());

               client.addCookie(newCookie);
           } else {
                               //for whatever reason the session information couldn't be obtained,
                               //take action here
           }
       }
于 2013-08-20T12:18:02.820 回答