【问题标题】:how can send a json frame to mysever hear i can reserve a json and i wnd send the data如何将 json 帧发送到 mysever 听到我可以保留 json 并发送数据
【发布时间】:2016-01-20 10:22:43
【问题描述】:

我发布了用于从服务器读取数据的代码,但我不知道如何向服务器发送 json 帧。

我要发送数据字符串。

try {
    URL url = new URL(params[0]);
    con = (HttpURLConnection)url.openConnection();
    con.connect();

    InputStream in = con.getInputStream();
    red = new BufferedReader(new InputStreamReader(in));
    String line = "";
    buffer = new StringBuffer();
    while ((line=red.readLine())!= null){
        buffer.append(line);
}
return buffer.toString();

【问题讨论】:

    标签: android json post


    【解决方案1】:

    我假设您正在尝试将post 一些JSON 对象转换为URL

    使用HttpURLConnection 进行连接时,如果您确实在URL 上发布了某些内容,则可以将其设置为这是一个POST 标头请求。

    之后,您可以使用DataOutputStream 实例写入(POST)您的JSON 数据类似这样。

    我写了一个sn-p,你可以查看,代码也可以在Github上找到

    private class MyTask extends AsyncTask<Void, Void, Void> {
    
        @Override
        protected Void doInBackground(Void... params) {
    
            try {
                /**
                 * Kindly change this url string with your own, where you want to post your json data
                 */
                URL url = new URL("");
    
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setDoOutput(true);
                // when you are posting do make sure you assign appropriate header
                // In this case POST.
    
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.connect();
    
                // like this you can create your JOSN object which you want to send
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("email", "dddd@gmail.com"); //dummy data
                jsonObject.addProperty("password", "password");// dummy data
    
                // And this is how you will write to the URL
                DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
                wr.writeBytes(jsonObject.toString());
                wr.flush();
                wr.close();
    
                Log.d("TAG", "" + IOUtils.toString(httpURLConnection.getInputStream()));
    
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    

    此代码使用 apache-common-io 从输入流中获取字符串,如果您愿意,可以更改它。

    【讨论】:

    • @ullaaskrishnan,如果你能接受答案,那就太好了:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多