之前一直是以GET的方式来请求数据,今天有个需求是以post的方式来获取数据,记录下。post 的参数有2种,一种是以string型的json格式数据,另一种是Map格式的数据

代码很简单,基本是一些流的操作和post格式设置。
代码如下:

/**
     *
     * @param url
     * @param isPostByJsonData 是否是String类型的json格式
     * @param jsonData  String类型的json格式数据
     * @param params map类型的数据
     */
    public void getDataByPost(String url, boolean isPostByJsonData, String jsonData, Map<String, String> params){
        InputStream inputStream = null;
        HttpURLConnection urlConnection = null;
        PrintWriter printWriter = null;
        BufferedReader bufferReader = null;

        InputStreamReader inputRader = null;
        StringBuffer contentBuffer = new StringBuffer();
        try {
            URL url1 = new URL(url);
            urlConnection = (HttpURLConnection) url1.openConnection();
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);

            StringBuffer stringBufParams = new StringBuffer();
            if(isPostByJsonData){
                stringBufParams.append(jsonData);
            }else {
                if(params != null){
                    for (Map.Entry<String, String> entry : params.entrySet()) {
                        stringBufParams.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                    }
                    stringBufParams.deleteCharAt(stringBufParams.length() - 1);
                }
            }

            printWriter = new PrintWriter(urlConnection.getOutputStream());
            printWriter.print(stringBufParams);
            printWriter.flush();

            int statusCode = urlConnection.getResponseCode();
            if (statusCode == 200){
                inputStream =urlConnection.getInputStream();
                inputRader = new InputStreamReader(inputStream, "utf-8");
                bufferReader = new BufferedReader(inputRader);
                String line = null;
                while (null != (line = bufferReader.readLine())) {
                    contentBuffer.append(line);
                }

                String dd = contentBuffer.toString();
                Log.e("xxx", "NetUtils dd = "+dd);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (printWriter != null) {
                    printWriter.close();
                }
            } catch (Exception e) {
            }
        }
    }

注意了,如果是Android开发,一定要在子线程中调用该方法,不然会crash.