HTTP协议使用JSON发送和接收数据

public static JSONObject httpInterfaceForJson(String requestUrl, String requestMethod, JSONObject fullJson) {
        String res = "";
        StringBuffer buffer = new StringBuffer();
        HttpURLConnection httpUrlConn = null;
        try {
            URL url = new URL(requestUrl);
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
//            httpUrlConn.setRequestProperty("Accept", "text/plain");
            httpUrlConn.setRequestProperty("Content-Type", "application/json");
            httpUrlConn.setRequestMethod(requestMethod);
            httpUrlConn.getOutputStream().write(fullJson.toString().getBytes("UTF-8"));
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            res = buffer.toString();
        } catch (ConnectException var21) {
        } catch (Exception var22) {
        } finally {
            try {
                httpUrlConn.disconnect();
            } catch (Exception var20) {
            }
        }
        return JSONObject.parseObject(res);
    }

猜你喜欢

转载自www.cnblogs.com/chonghaojie/p/9152357.html