怎么能发送一个json帧到mysever听到我可以保留一个json,我会发送数据

时间:2016-01-20 10:22:44

标签: android json post

我发布了用于从服务器读取数据的代码,但我不知道如何将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();

1 个答案:

答案 0 :(得分:0)

我认为你试图将post某个JSON对象改为URL

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

之后,您可以使用DataOutputStream实例来编写(POSTJSON这样的数据。

我已经编写了一个可以检查的代码段,代码也可以在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从输入流中获取String,如果您希望可以更改它。