2013-04-22 34 views
0

我对android编程很陌生。我有一个程序使用套接字连接到远程主机,欺骗一个http请求,并解析结果。出于某种原因,我的套接字无法连接到主机。我已经在独立环境中测试了该程序,它连接并正常工作。我继续前进,隔离了我需要的功能,并将其包含在我的活动课程中,以此方式进行调用。我也尝试过静态调用它,以及执行一个异步对象并从那里调用它。在我的Android模拟器上的互联网工作从浏览器,我已经添加到我的Android清单。下面的代码显示了我现在的立场。我需要做什么?使用android模拟器创建套接字到远程HTTP服务器

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)); 


       } 




     } 
    } 
} 

回答

0

这里发生的事情是常有的事,你想你的应用程序的 主线程上执行一些长期运行的操作。

这是什么意思,主线程负责更新用户界面,强制执行顺畅的体验,如果android检测到你正在做一些长时间运行的操作将被阻止,它会强制关闭应用程序,让你知道这是不好的。

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

此外,建立socket连接,你应该做的:

conn = new Socket(InetAddress.getByName(new URL("http://www.delta.com").getHost()), 80); 
dis = new DataInputStream(conn.getInputStream()); 
dos = new DataOutputStream(conn.getOutputStream()); 
+0

我使用的AsyncTask尝试。我更新了我的问题,显示我是如何使用它的。似乎仍然是这个问题? – 2013-04-22 01:37:53

+0

我已经修复了您当前的代码,请参阅我的更新回答。请接受它是否解决了您的问题。 – wangyif2 2013-04-22 01:57:49

+0

它的确如此,谢谢! – 2013-04-22 03:27:01

相关问题