使用 http post 将 JSON object 发送到 API

Sending JSON object to API by using http post

我要添加header"Content-Type""application/json"。但是由于 android.

中的 api 23,我无法做到这一点
                OutputStream os= null;
                os=httpclient.getOutputStream();
                BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(os));

                JSONObject jsonobj = new JSONObject();
                jsonobj.put("Name","alpha");
                jsonobj.put("Status","Active");
                jsonobj.put("Type","Admin");
                jsonobj.put("Address","beta");
                jsonobj.put("Password","333");
                jsonobj.put("PhoneNumber",123);

                bw.write(jsonobj.toString());
                os.close();

我假设您正在尝试对某些 API 进行网络调用,它希望您将 Headers 添加到您正在进行的 HTTP 调用中,并且 content-type数据为JSON.

如果是这种情况,那么您必须将 Headers 指定给您尝试连接的相应 class 实例。

例如,如果您使用 HttpURLConnection 那么它看起来像这样

            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST"); // hear you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
            httpURLConnection.setRequestProperty("Content-Type", "application/json"); // here you are setting the `Content-Type` for the data you are sending which is `application/json` 
            httpURLConnection.connect();

当您将一些数据发布到 HttpURLConnection 的实例时,您可以这样做...

            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("para_1", "arg_1");
            jsonObject.addProperty("para_2", "arg_2");

            DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
            wr.writeBytes(jsonObject.toString());
            wr.flush();
            wr.close();