Android Get方式发送信息

程序需要用到Internet权限,所以需要在AndroidManifest.xml添加

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

MainActivity.java

public class MainActivity extends Activity {
    private TextView info=null;
    private Button Btn01=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_main);
        this.info=(TextView)super.findViewById(R.id.info);
        this.Btn01=(Button)super.findViewById(R.id.Btn01);
        this.Btn01.setOnClickListener(new OnClickListenerImpl());

    }
    
    private class OnClickListenerImpl implements OnClickListener{

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            System.out.println(">>Button");
            switch (v.getId()) {
            case R.id.Btn01:
                try {
                    System.out.println(">>btn01");
                    //URL url=new URL("http","172.17.8.28",80,"android.ashx");
                    URL url=new URL("http","t.sina.com",80,"/");
                    HttpURLConnection conn=(HttpURLConnection)url.openConnection();
                    byte data[]= new byte[512]; 
                    int len=conn.getInputStream().read(data);//输入流读取
                    System.out.println(">>len="+len);
                    if(len>0){
                        String temp= new String(data,0,len).trim();
                        //flag=Boolean.parseBoolean(temp); //取出里面的bool数据
                        System.out.println(">>"+temp);
                        MainActivity.this.info.setText(temp);
                    }
                    conn.getInputStream().close();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    System.out.println("Error:"+e.toString());
                }
                break;

            default:
                break;
            }
        }
        
    }

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >
    <Button
        android:id="@+id/Btn01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="测试" />
    <TextView
        android:id="@+id/info"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

 

 

posted @ 2013-10-30 10:16  寂静之秋  阅读(283)  评论(0编辑  收藏  举报
哈尔滨八零网