java Http get 和 post 请求的一般流程

来源:互联网 发布:emlog博客源码下载 编辑:程序博客网 时间:2024/06/10 02:12

一、GET请求

public String get(String urlString){HttpURLConnection conn = null;        InputStream inputStream = null;        //url无效        if (TextUtils.isEmpty(urlString)) {            return "" ;        }                try {            // 首先指定服务器的路径URL            URL url = new URL(urlString);            //打开连接            conn = (HttpURLConnection) url.openConnection();                        //设定连接属性            //一定要在getContentLength、getResponseCode等调用之前设置属性,但可以在connct之后?            conn.setRequestMethod("GET");            conn.setConnectTimeout(5000);            conn.setReadTimeout(5000);            //设定头部信息            conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");            conn.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");            conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");            conn.setRequestProperty("Cache-Control", "max-age=0");  //            conn.setRequestProperty("Host", "www.baidu.com");            conn.setRequestProperty("Proxy-Connection", "keep-alive");            conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36");            //建立实际连接(可以省略,打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。 )            conn.connect();                        //发出请求,并取得返回结果                       //此连接的 URL 引用的资源的内容长度,或者如果内容长度未知,则返回 -1            int len = conn.getContentLength();            System.out.println("len:"+len);                        //如果无法从响应中识别任何代码(即响应不是有效的 HTTP),则返回 -1。 (200:请求成功)            int rescode = conn.getResponseCode();            System.out.println("respon code:"+rescode);                        //读取响应报文头部信息            Map<String, List<String>> map = conn.getHeaderFields();            for(String key: map.keySet())            {                System.out.println(key + "--->" + map.get(key) );            }                        //读取响应报文正文信息            inputStream = conn.getInputStream();            InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);            String line;            while((line = bufferedReader.readLine()) != null){                result += "\n" + line;           }        } catch (Exception e) {            // TODO: handle exception            System.out.println(e);        }finally{            try {                if (inputStream != null) {                    inputStream.close();                }                                if (conn != null) {                    conn.disconnect();                }            } catch (Exception e2) {                // TODO: handle exception                System.out.println(e2);            }                                }                     try {            byte[] bs = result.getBytes();            return new String(bs,"utf-8");        } catch (Exception e) {            // TODO: handle exception            System.out.println(e);            return "";        }           }



二、POST

public String post(String urlString)    {        String result = "";           //url无效        if (TextUtils.isEmpty(urlString)) {            return "";        }                try {            // 首先指定服务器的路径URL            URL url = new URL(urlString);            //打开连接            HttpURLConnection conn = (HttpURLConnection) url.openConnection();                        //设定连接属性            conn.setRequestMethod("POST");            conn.setReadTimeout(5000);            conn.setConnectTimeout(5000);                        //设定头部信息            conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");            conn.setRequestProperty("connection", "keep-alive");            conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36");            //发送POST请求必须设置如下两行            conn.setDoOutput(true);            conn.setDoInput(true);                        conn.connect();                        /**             * 下面取得并向网络流输出请求正文             */            //构造JSON内容            JSONObject bodyJsonObject = new JSONObject();            bodyJsonObject.put("token", "12345678901234567890123456789012");            bodyJsonObject.put("method", "create");            bodyJsonObject.put("path", "/newFolder");                        JSONObject msgJsonObject = new JSONObject();            msgJsonObject.put("header", createHeaderJsonString());            msgJsonObject.put("body", bodyJsonObject);                        // 创建一个新的数据输出流,将数据写入指定基础输出流            //取得网络流的输出流            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());                        // 将字符串按字节顺序 写出 到基础输出流中            System.out.println("msg:" + msgJsonObject.toString());            dos.write(msgJsonObject.toString().getBytes());            dos.flush();                        //发出请求,并 获取服务器反馈的信息            InputStream inputStream = conn.getInputStream();            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);            String line;            while((line = bufferedReader.readLine()) != null){                result += "\n" + line;            }                    } catch (Exception e) {            // TODO: handle exception            System.out.println(e);        }finally{                    }                return result;    }        public SONObject createHeaderJsonString() throws JSONException {        JSONObject jsonObject = new JSONObject(                "{'msg_id':'1ADDFC6F9089423582B2135D126AB6EB',"                + "'module':'CloudDisk',"                + "'action':'get',"                + "'send_to':'lly12345678',"                + "'length':1024}");        return jsonObject;    }    


0 0