使用http post将JSON对象发送到API

时间:2016-01-10 06:17:05

标签: android http-headers http-post

我想添加标题" Content-Type" "应用/ JSON&#34 ;.但由于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();

1 个答案:

答案 0 :(得分:0)

我假设您尝试向某些API进行网络通话,希望您将Headers添加到您正在进行的HTTP来电和content-type数据是JSON

如果是这种情况,那么您必须将实例的标题指定到您尝试连接的相应类。

例如,如果您使用的是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();