使用http post将JSON对象发送到API [英] Sending JSON object to API by using http post

查看:355
本文介绍了使用http post将JSON对象发送到API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加标题Content-Typeapplication / json。但由于android中的api 23,我无法做到这一点。

I want to add header "Content-Type" "application/json". But I am not been able to do this due to api 23 in android.

                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 ,希望您将标题添加到 HTTP 您正在拨打电话,内容类型数据 JSON

I assume that you are trying to make a network call to some API which expects you to add Headers to the HTTP calls you are making and the content-type data is JSON.

如果是你的情况那么你必须指定实例的Headers到你想要连接的各个类..

If that is your case then you would have to specify the Headers to the instance to respective class with which you are trying to connect..

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

for example if you are using HttpURLConnection then it would look like this

            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的实例你可以这样做......

and when you are posting some data to the instance of the HttpURLConnection you can do it like this...

            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();

这篇关于使用http post将JSON对象发送到API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆