0

我对android编程很陌生。我有一个程序,它使用套接字连接到远程主机、欺骗 http 请求并解析结果。由于某种原因,我的套接字无法连接到主机。我已经在独立环境中测试了该程序,它可以连接并正常工作。我继续并隔离了我需要的函数,并将其包含在我的活动类中以这种方式调用它。我也尝试过静态调用它,以及执行一个异步对象并从那里调用它。我的 android 模拟器上的互联网可以通过浏览器运行,我添加了

 <uses-permission android:name="android.permission.INTERNET"/>

到我的 android 清单。下面的代码显示了我现在的位置。我需要做什么?

public class FlightNumResults extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    Intent intent = getIntent();
    String value = intent.getStringExtra("input"); //if it's a string you stored.
    //super.onCreate(savedInstanceState);
    System.out.println("HULLO");
    System.out.println(value);
    setContentView(R.layout.loading);

    Log.i("Excecution", "Complete");
    Hashtable<String, String> table = flightNumInfo(value);
    if (table == null)
        System.out.println("NULL");

    TableLayout results = (TableLayout) findViewById(R.id.resultTable);

    TableRow rowLabels = new TableRow(this);
    TableRow rowResults = new TableRow(this);
    rowLabels.setGravity(Gravity.CENTER);

    TableRow.LayoutParams params = new TableRow.LayoutParams();
    params.span = 4;

    //Column 1
    TextView destLabel = new TextView(this);  
    destLabel.setText("Destination");  
    destLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);  
    TextView destResult = new TextView(this);  
    destResult.setText(table.get("destination"));  
    destResult.setGravity(Gravity.CENTER_HORIZONTAL);  

    rowLabels.addView(destLabel);  
    rowResults.addView(destResult);
    //Column 2
    TextView gateLabel = new TextView(this);  
    destLabel.setText("Gate");  
    destLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);  
    TextView gateResult = new TextView(this);  
    destResult.setText(table.get("gate"));  
    destResult.setGravity(Gravity.CENTER_HORIZONTAL);  

    rowLabels.addView(gateLabel);  
    rowResults.addView(gateResult);
  //Column 3
    TextView scheduledLabel = new TextView(this);  
    destLabel.setText("Scheduled");  
    destLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);  
    TextView scheduledResult = new TextView(this);  
    destResult.setText(table.get("scheduled"));  
    destResult.setGravity(Gravity.CENTER_HORIZONTAL);  

    rowLabels.addView(scheduledLabel);  
    rowResults.addView(scheduledResult);
  //Column 4
    TextView estimatedLabel = new TextView(this);  
    destLabel.setText("estimated");  
    destLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);  
    TextView estimatedResult = new TextView(this);  
    destResult.setText(table.get("scheduled"));  
    destResult.setGravity(Gravity.CENTER_HORIZONTAL);  

    rowLabels.addView(estimatedLabel);  
    rowResults.addView(estimatedResult);

    results.addView(rowLabels);
    results.addView(rowResults);

    setContentView(R.layout.activity_flightnum_results);





}
public Hashtable<String, String> flightNumInfo(String flightNum) {

    Hashtable<String, String> table = new Hashtable<String, String>();
    System.out.println("Initializing socket");
    try {
        String request = "GET /flifo/servlet/DeltaFlifo?airline_code=DL&flight_number="
                + flightNum
                + "&flight_date="
                + DateCalc.getSlashDateAndTime()
                + "&request=main&DptText=ATL HTTP/1.1";

        Socket conn = new Socket(InetAddress.getByName("www.delta.com"), 80);
        System.out.println("initialized");
        PrintWriter wr = new PrintWriter(conn.getOutputStream());

        wr.println(request);
        wr.println("Host: www.delta.com");
        wr.println("Referer: http://www.delta.com/flifo/servlet/DeltaFlifo?airline_code=DL&request=main");
        wr.println("Connection: close\n");
        wr.flush();

        Scanner in = new Scanner(conn.getInputStream());
        String myResp = new String();
        String ans = new String();

        do {
            ans = in.nextLine();
            myResp += ans;
        } while (ans.indexOf("<span class=\"detailsLabel\"><br />") < 0);

        wr.close();
        in.close();
        // System.out.println(myResp);
        Pattern p = Pattern
                .compile("<td class=\"tableCell\" align=\"left\">&nbsp;\\s+Atlanta\\s+"
                        + "<a href=\"/content/www/en_US/traveling-with-us/airports-and-aircraft/airports/atlanta.html\">"
                        + "<!-- mp_trans_disable_start -->\\(ATL\\)<!-- mp_trans_disable_end --></a>\\s+<br />&nbsp;(.*?)"
                        + "<br />&nbsp; Gate <!-- mp_trans_disable_start -->([A-Z0-9]{2,3})<!-- mp_trans_disable_end -->\\s+"
                        + "</td>\\s+<td class=\"tableCell\">\\s+&nbsp;([A-Za-z0-9:]{6,9})<br />\\s+&nbsp;(.*?)</td>\\s+"
                        + "<td class=\"tableCell\">\\s+&nbsp;([a-z0-9*?:]{6,9}|[a-zA-Z\\s]{6,9})<br />\\s+&nbsp;(.*?)</td>\\s+" 
                        + "<td class=\"tableCell\">&nbsp;(.*?)\\(([A-Z]{3})\\)");


        Matcher m = p.matcher(myResp);
        if (m.find()) {
            table.put("number", flightNum);
            table.put("gate", m.group(2));
            table.put("scheduled", m.group(3));
            table.put("estimated", m.group(5));
            table.put("destination", m.group(8));

            return table;
        }
    } catch (Exception e) {
        return null;
    }
    return null;
}

}

这是我的代码使用 AsyncTask 的样子。

public class FlightNumResults extends Activity {

public String flightNum;
public Hashtable<String, String> table;

@Override
protected void onCreate(Bundle savedInstanceState) {
    Intent intent = getIntent();
    flightNum = intent.getStringExtra("input"); // if it's a string you
                                                // stored.
    super.onCreate(savedInstanceState);
    System.out.println("HULLO");
    // System.out.println(value);

    setContentView(R.layout.loading);

    Log.i("Excecution", "Complete");
    FlightInfo fi = new FlightInfo();
    fi.execute();
    fi.flightNumInfo(flightNum);
    // Hashtable<String, String> table = fi.flightNumInfo(value);

    // System.out.println(table.get("destination"));

    // setContentView(R.layout.activity_flightnum_results);



}

public class FlightInfo extends AsyncTask<Void, Void, Void> {
    public Socket conn;
    public PrintWriter wr;
    public DataInputStream dis;
    public DataOutputStream dos;
    @Override
    protected Void doInBackground(Void... params) {
        try {
             conn = new Socket(InetAddress.getByName("www.delta.com"), 80);
        }catch (Exception e){
            Log.i("AsyncTank", "Can't create socket");
        }
        if (conn.isConnected()){
            try {
                dis = (DataInputStream)conn.getInputStream();
                dos = (DataOutputStream)conn.getOutputStream();
                Log.i("AsyncTank", "doInBackgoung: Socket created, Streams assigned");

            } catch (IOException e) {
                // TODO Auto-generated catch block
                Log.i("AsyncTank", "doInBackgoung: Cannot assign Streams, Socket not connected");
                e.printStackTrace();
            }
        } else {
            Log.i("AsyncTank", "doInBackgoung: Cannot assign Streams, Socket is closed");
        }
        return null;

        }
    protected void onPostExecute(Boolean result) {
        if (result) {
            Log.i("AsyncTask", "onPostExecute: Completed with an Error.");

        } else {
            Log.i("AsyncTask", "onPostExecute: Completed.");

        }
        setContentView(R.layout.activity_flightnum_results);

    }



        public  void flightNumInfo(String flightNum) {

              table = new Hashtable<String, String>();

                String request = "GET /flifo/servlet/DeltaFlifo?airline_code=DL&flight_number="
                        + flightNum
                        + "&flight_date="
                        + DateCalc.getSlashDateAndTime()
                        + "&request=main&DptText=ATL HTTP/1.1";

                //Socket conn = new Socket(InetAddress.getByName("www.delta.com"), 80);

                wr = new PrintWriter(dos);

                wr.println(request);
                wr.println("Host: www.delta.com");
                wr.println("Referer: http://www.delta.com/flifo/servlet/DeltaFlifo?airline_code=DL&request=main");
                wr.println("Connection: close\n");
                wr.flush();

                Scanner in = new Scanner(dis);
                String myResp = new String();
                String ans = new String();

                do {
                    ans = in.nextLine();
                    myResp += ans;
                } while (ans.indexOf("<span class=\"detailsLabel\"><br />") < 0);

                wr.close();
                in.close();

                // System.out.println(myResp);
                Pattern p = Pattern
                        .compile("<td class=\"tableCell\" align=\"left\">&nbsp;\\s+Atlanta\\s+"
                                + "<a href=\"/content/www/en_US/traveling-with-us/airports-and-aircraft/airports/atlanta.html\">"
                                + "<!-- mp_trans_disable_start -->\\(ATL\\)<!-- mp_trans_disable_end --></a>\\s+<br />&nbsp;(.*?)"
                                + "<br />&nbsp; Gate <!-- mp_trans_disable_start -->([A-Z0-9]{2,3})<!-- mp_trans_disable_end -->\\s+"
                                + "</td>\\s+<td class=\"tableCell\">\\s+&nbsp;([A-Za-z0-9:]{6,9})<br />\\s+&nbsp;(.*?)</td>\\s+"
                                + "<td class=\"tableCell\">\\s+&nbsp;([a-z0-9*?:]{6,9}|[a-zA-Z\\s]{6,9})<br />\\s+&nbsp;(.*?)</td>\\s+" 
                                + "<td class=\"tableCell\">&nbsp;(.*?)\\(([A-Z]{3})\\)");


                Matcher m = p.matcher(myResp);
                if (m.find()) {
                    table.put("number", flightNum);
                    table.put("gate", m.group(2));
                    table.put("scheduled", m.group(3));
                    table.put("estimated", m.group(5));
                    table.put("destination", m.group(8));


                }




        }
    }
}
4

1 回答 1

0

这里发生的事情很常见,您正试图在应用程序的主线程上执行一些长时间运行的操作。

这意味着,主线程负责更新 UI,以强制执行流畅的体验,如果 android 检测到您正在执行一些将阻塞的长时间运行操作,它将强制关闭应用程序,让您知道这很糟糕。

有许多替代解决方案,例如 AsynTask 或 IntentService。

此外,要建立套接字连接,您应该执行以下操作:

conn = new Socket(InetAddress.getByName(new URL("http://www.delta.com").getHost()), 80);
dis = new DataInputStream(conn.getInputStream());
dos = new DataOutputStream(conn.getOutputStream());
于 2013-04-22T00:50:29.483 回答