HTTP通訊GET方式

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class mainActivity extends Activity {
    TextView tv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.tv1);
        String resultData = "";
        // GET方法須要權限
        String httpurl = "http://10.0.2.2:8080/dem/index.jsp";
        // 建立URL
        URL url = null;
        try {
            // 構建URL對象
            url = new URL(httpurl);
        }
        catch(MalformedURLException e) { 
            e.printStackTrace();
        }
        if(url != null) {
            try {
                // 使用HttpURLConnection打開鏈接
                HttpURLConnection urlConn = (HttpURLConnection) url
                        .openConnection();
                // 獲得讀取的內容 (流)
                InputStreamReader in = new InputStreamReader(
                        urlConn.getInputStream());
                // 爲輸出建立BufferedReader
                BufferedReader buffer = new BufferedReader(in);
                String inputLine = null;
                while((inputLine = buffer.readLine()) != null) {
                    // 加換行
                    resultData += inputLine + "\n";
                }
                // 關閉InputStreamReader
                in.close();
                // 斷開http
                urlConn.disconnect();
                if(resultData != null) {
                    tv.setText(resultData);
                }
                else {
                    tv.setText("讀取的內容爲NULL");
                }

            }
            catch(IOException e) { 
                Log.e("a", e.getMessage());
            }
        }

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


版權聲明:本文爲博主原創文章,未經博主容許不得轉載。html

相關文章
相關標籤/搜索