0

我目前的问题是我正在尝试.post()使用慢速服务器的用户名和密码。当我绕过在主线程上运行我的网络代码时,我的方法工作正常。我决定停止偷懒并将我的代码移动到 AsyncTask 线程,但是 JSOUP 开始忽略.timeout()我设置的时间,这导致了 408 错误。

这是我的代码。用户名和密码被审查。网址也被审查。Logcat 显示代码工作正常。

package com.example.androidgenparsetest;



import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
import java.util.Map;

    import android.os.AsyncTask;

    import android.widget.TextView;

    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;

    public class MainActivity extends Activity 
    {


    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        //StrictMode.setThreadPolicy(policy); 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new GetGenesis().execute("ca.com","ca3");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    private class GetGenesis extends AsyncTask<String, Void, Document> 
    {
        protected Document doInBackground(String... UserPass) 
        {
            Document doc2 = null;
              try 
              {
                Connection.Response res = Jsoup
                        .connect("http://j_security_check")
                        .data("j_username",UserPass[0],"j_password",UserPass[1])
                        .method(Method.POST)
                        .userAgent("Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46 Safari/536.5")
                        .timeout(2*1000)
                        .ignoreHttpErrors(true) 
                        .execute();
                Map<String, String> cookies = res.cookies();

                doc2 = Jsoup
                        .connect("/j_security_check")
                        .data("j_username",UserPass[0],"j_password",UserPass[1])
                        .method(Method.POST)
                        .userAgent("Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46 Safari/536.5")
                        .timeout(2*1000)
                        .ignoreHttpErrors(true) 
                        .cookies(cookies)
                        .get();


              }
              catch (IOException e) 
              {
                e.printStackTrace();

              }
              return doc2;
        }

        protected void onPostExecute(Document doc) 
        {
          Document doc2=doc;
          TextView htmltext=(TextView)findViewById(R.id.htmltext);
          htmltext.setText(doc2.text());
        }


    }
}
4

3 回答 3

0
HttpURLConnection urlConnection = null;
HttpURLConnection connection = null;
try {
    URL url = new URL(Your_Url_asString);
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.connect();

    // Get cookies
    List cookieList = urlConnection.getHeaderFields().get("Set-Cookie");
    String cookie = "";
    if (cookieList != null) {
        for (String cookieTemp : cookieList) {
            cookie = cookieTemp;
        }
    }

    //second connection
    String query = "j_username="+UserPass[0]+"&j_password="+UserPass[1];
    URL url = new URL(Your_Url2_asString);    
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Cookie", cookie);
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setReadTimeout(10000);
    Writer writer = new OutputStreamWriter(connection.getOutputStream());
    writer.write(query);
    writer.flush();
    writer.close();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (urlConnection != null) {
        urlConnection.disconnect();
    }
}

注意:对于较低版本(小于 froyo)使用“set-cookie”而不是“Set-Cookie”

于 2013-03-12T05:10:58.980 回答
0

确保Jsoup.jar在 libs 文件夹中。

于 2013-04-30T06:44:31.107 回答
0

像这样修改onCreate

 Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) 
{
    //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    //StrictMode.setThreadPolicy(policy); 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     mContext = this;

     final GetGenesis tsk = new  GetGenesis();
     tsk .execute("ca.com","ca3");

     //setting timeout thread for async task
            Thread thread1 = new Thread(){
            public void run(){
                try {
                    tsk.get(30000, TimeUnit.MILLISECONDS);  //set time in milisecond(in this timeout is 30 seconds

                } catch (Exception e) {
                    tsk.cancel(true);                           
                    ((Activity) mContext).runOnUiThread(new Runnable()
                    {
                         @SuppressLint("ShowToast")
                        public void run()
                         {
                            Toast.makeText(mContext, "Time Out.", Toast.LENGTH_LONG).show();
                            finish(); //will close the current activity comment if you don't want to cose current activity.                             
                         }
                    });
                }
            }
        };
        thread1.start();

                               }
}
于 2013-12-04T13:04:39.667 回答