Android http请求

来源:互联网 发布:php oa系统源码 编辑:程序博客网 时间:2024/06/06 07:47

android http请求其实很简单,这里我就不多废话了,直接上代码
重点内容
public class HttpUtil {

public static String Path_url = "http://192.168.1.109:8080/DrawServer/servlet/Draw?";public static String Path_url_login = "http://192.168.1.109:8080/DrawServer/servlet/Login?";public HttpUtil() {    // TODO Auto-generated constructor stub}public synchronized static String getConnection(String path) {        //path为需要访问的url        //http://192.168.1.109:8080/DrawServer/servlet/Draw?        URL url = new URL(path);        //System.out.println("paht == " + path);        HttpURLConnection connection = (HttpURLConnection) url                .openConnection();        connection.setConnectTimeout(3000);//设置连接超时        connection.setRequestMethod("GET");//设置请求方式        connection.setDoInput(true);        int code = connection.getResponseCode();//获得请求码,每个请求码代表网上都可以查到,如果是200就是请求成功    //  System.out.println("----Code-->>   " + code);        if (code == 200) {            return changeInPutStream(connection.getInputStream());//获取inputsteam,读取数据        }    } catch (MalformedURLException e) {        // TODO Auto-generated catch block        System.out.println("------>>    URL  ");    } catch (IOException e) {        // TODO Auto-generated catch block        System.out.println("------>>    connection  ");    }    return "";}private String changeInPutStream(InputStream inputStream) {    // TODO Auto-generated method stub    String JsonString = "";    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();    int len;    byte[] data = new byte[1024];    try {        while ((len = inputStream.read(data)) != -1) {            outputStream.write(data, 0, len);        }        JsonString = new String(outputStream.toByteArray(), "UTF-8");    } catch (IOException e) {        // TODO Auto-generated catch block        System.out.println("------>>    outputStream  ");    }    return JsonString;}

}

0 0
原创粉丝点击