java post 获取相应内容和状态码

Map map = new HashMap();
		
		PrintWriter out = null;
        BufferedReader in = null;
        HttpURLConnection conn = null;
        String res = "";
        
        try {
            URL realUrl = new URL(url);
            
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            
            out = new PrintWriter(conn.getOutputStream());
            
            out.print(str);
            out.flush();
            
            conn.connect();
            map.put("code", conn.getResponseCode() + "");
            
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            
            String line;
            while ((line = in.readLine()) != null) {
                res += line;
            }
        } catch (Exception e) {
        	System.out.println( ",发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        map.put("res", res);
        return map;

你可能感兴趣的:(java基础)