天天看点

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"/>