如何使用post将json对象发送到Web服务器

时间:2016-05-26 18:20:53

标签: java android json jsonobject

我想将json对象发送到我的网络服务器。我在以前版本的代码中进行了一些更改,我将字符串发送到我的网络服务器。但它不适用于发送对象。请帮忙!

package com.digitalapplication.eventmanager;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class BackgroundTask extends AsyncTask<JSONObject,Void,String> {
    Context ctx;
    BackgroundTask(Context ctx)
    {
        this.ctx=ctx;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(JSONObject... params) {
        String inserturl="http://192.168.10.4/webapp/register.php";
        String method="register";
        if(method.equals("register"))
        {

            try {
                URL url=new URL(inserturl);
                HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                OutputStream OS=httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(OS,"UTF-8"));

                bufferedWriter.write(params.toString());

                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                InputStream IS=httpURLConnection.getInputStream();
                IS.close();
                return "Data Saved in server...";
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return "not saved in server";
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String  result) {
        Toast.makeText(ctx, result,Toast.LENGTH_SHORT).show();
    }


}


        return "not saved in server";
    }

这里是对backgroundTask类的调用

BackgroundTask backgroundTask=new BackgroundTask(this);

                JSONObject jsonObject=new JSONObject();
                try {
                    jsonObject.put("gid","asd");
                    jsonObject.put("uid","asdd");
                    jsonObject.put("name","assgd");
                    jsonObject.put("phone","agssd");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                backgroundTask.execute(jsonObject);

这是服务器端的PHP脚本。

的init.php

<?php
$db_name="eventmanager";
$mysql_user="root";
$mysql_pass="";
$server_name="localhost";
$con=mysqli_connect($server_name, $mysql_user,$mysql_pass,$db_name);
if(!$con){
    //echo"Connection Error...".mysqli_connect_error();
}
else{
    //echo"<h3>Connection success....</h3>";
}

?>

register.php

 <?php
    require "init.php";
    $obj = $_POST["obj"];
    $args = json_decode($obj, true);
    foreach($args as $key=>$field){
        $gid = $field["gid"];
        $uid = $field["uid"];
        $name = $field["name"];
        $phone = $field["phone"];
        $sql_query="insert into groups values('$gid','$uid','$name','$phone');";
        mysqli_query($con,$sql_query);

    }

    ?>

3 个答案:

答案 0 :(得分:1)

我们还需要更多,你看到的错误是什么?

编辑,如果您看到使用省略号作为参数并在其上调用toString。这只会给你输出像[Ljava.lang.String; @ 659e0bfd,这是无效的json。尝试

params[0].toString()

看看它是否有效。

答案 1 :(得分:1)

尝试在AsyncTask中使用此方法,这是一个功能性示例。

// ......
private static final String USER_AGENT = "Mozilla/5.0";

public static String sendPost(String url, String data) throws Exception {

    HttpURLConnection  con = (HttpURLConnection) new URL(url).openConnection();

    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept","*/*");
    con.setRequestProperty("Content-Type","application/json");

    con.setDoOutput(true);
    con.setDoInput(true);

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(data);
    wr.flush();
    wr.close();
    data = null;

    System.out.println("\nSending 'POST' request to URL : " + url);

    InputStream it = con.getInputStream();
    InputStreamReader inputs = new InputStreamReader(it);

    BufferedReader in = new BufferedReader(inputs);
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }

    in.close();

    System.out.println("Server says : " + response.toString());
    return response.toString();
}

你的代码看起来不错,但我们来试试吧。如果此操作失败,则问题出在您的服务器上。

如果您的服务器中有任何输出,请发布。或者您也可以在数据库插入之前在PHP脚本中打印值,以查看值是否真的到达。

答案 2 :(得分:0)

最后我找到了解决方案。我错过了以下代码行,它会在将数据发送到服务器之前对其进行编码。

 String data= URLEncoder.encode("obj", "UTF-8") +"="+URLEncoder.encode(params[0].toString(), "UTF-8");

                bufferedWriter.write(data);