天天看點

Android使用HttpURLConnection請求網絡資源

1.打開伺服器:

打開C:\Program Files\apache-tomcat-6.0.37\bin\startup.bat,

浏覽器輸入http://localhost:8080測試伺服器是否開啟成功

2.将常用的參數封裝成一個類

UrlManager.java

public class UrlManager {
//官方模拟器通路本地Web伺服器使用IP 10.0.2.2
//真機使用本機的IP位址 ipconfig
public static final String BASE_URL="http://10.0.2.2:8080/HttpTest/";
//主畫面路徑
public static final String MAIN_VIEW="index.jsp";
}
           

2.編寫請求網絡的方法:

HttpUtil.java

package com.example.ygd.jreduch09.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtil {
public static String doGet(String u){
    HttpURLConnection con=null;
    InputStream is=null;
    StringBuilder sbd=new StringBuilder();
    try {
        URL url=new URL(u);
        con= (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(5*1000);  //設定逾時時間
        con.setReadTimeout(5*1000);     //設定讀取時間
//            con.setRequestMethod("GET");
        if(con.getResponseCode()==200){ //判斷是否連接配接成功
            is=con.getInputStream();    //擷取輸入
            int next=0;
            byte[] bt=new byte[1024];
            while((next=is.read(bt))!=-1){
                sbd.append(new String(bt),0,next);  //讀入到sbd中
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(con!=null){
            con.disconnect();
        }
    }
    return sbd.toString();
}
}
           

3.主函數使用異步任務類或者Handler方式來調用

4.最後,運作前不要忘了權重限

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