2010-11-17 47 views
0

我寫了這段代碼登錄到我的網站,並檢查我是否登錄。Android發佈連接SingleClientConnManager登錄

public class smerdLearning extends Activity { 
/** Called when the activity is first created. */ 
final HttpParams params = new BasicHttpParams(); 
final HttpClient client = new DefaultHttpClient(params); 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    String url, user, pwd, user_field, pwd_field; 

    url = "http://SMERDER.org/login/"; 


    user_field = "username"; 
    pwd_field = "password"; 
    user = "robert"; 
    pwd = "fanello"; 

    final List<NameValuePair> myList = new ArrayList<NameValuePair>(2); 
    myList.add(new BasicNameValuePair(user_field, user)); 
    myList.add(new BasicNameValuePair(pwd_field, pwd)); 


    final HttpPost post = new HttpPost(url); 

    Button login_button = (Button)findViewById(R.id.login_button); 

    login_button.setOnClickListener(new OnClickListener(){ 
     public void onClick(View v) { 
      try { 
       post.setEntity(new UrlEncodedFormEntity(myList)); 
      } catch (UnsupportedEncodingException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      try { 
       HttpResponse response = client.execute(post); 
       System.out.println("Am I logged in?"); 
       String am_i_logged= "http://smerder.smerder.org/api/am-i-logged-in/"; 

       try { 
        URLreader(am_i_logged, response); 
       } catch (Exception e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

void URLreader(String url, HttpResponse response) throws Exception{ 
    response = client.execute(new HttpGet(url)); 
    HttpEntity entity = response.getEntity(); 

    BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent())); 

    String inputLine; 

    while ((inputLine = in.readLine()) != null){ 
     System.out.println(inputLine); 
    } 
    in.close(); 
} 

}

但是,如果我看到了日誌,logcat中,我看到兩個警告: 3月11日至十七日:07:40.976:WARN/SingleClientConnManager(1195):確保釋放連接在分配另一個之前。

如何釋放連接?

回答

0

您的代碼正在執行2個http操作。

的URLreader呼叫之前,你有一個

HttpResponse response = client.execute(post); 

然後URLreader通話

void URLreader(String url, HttpResponse response) throws Exception{ 
    response = client.execute(new HttpGet(url)); 
    HttpEntity entity = response.getEntity(); 

    BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent())); 

    String inputLine; 

    while ((inputLine = in.readLine()) != null){ 
     System.out.println(inputLine); 
    } 
    in.close(); 
} 

你把自己的傳遞響應,並沒有上調用close在這流。某處(前或後URLreader),你需要

InputStream is = post.getEntity().getContent() 
if(is!=null) 
    is.close() 

您可能還需要在呼叫甩出去

post.getEntity().consumeContent() ; 

我沒有說,但看到它在示例代碼。