douju6651 2016-09-12 12:43
浏览 56

如何将jsonArray发送到android中的服务器?

I have created an Api which is used to add invitations in the database called as sendMultipleInvites. Now I want to implement this API in android. I am trying to create an AsyncTask to call the api. I have helper classes to connect to http server.

sendMultipleInvites.php

    <?php

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
ini_set('display_errors', '1');

require 'Invitation.php';

$jsonText = file_get_contents('php://input');

if(empty($jsonText))
{
    $response = array("status"=>-2,"message"=>"Empty request");
    die(json_encode($response));
}

$json = json_decode($jsonText);

$response = array();

foreach ($json as $jsn) {
    foreach($jsn as $j)
    {
        $sender_id = $j -> sender_id;
        $date= $j -> date;
        $invitee_no = $j -> invitee_no;
        $status = $j -> status;
        $user_name = $j -> user_name;
        $invitation = new Invitation($sender_id,$date,$invitee_no,$status,$user_name);
        $response[] = $invitation->sendMultipleInvites();

    }

}
echo(json_encode($response));
?>

serverRequest class:

  public class ServerRequest {
    String api;
    JSONObject jsonParams;

    public ServerRequest(String api, JSONObject jsonParams) {
        this.api = api;
        this.jsonParams = jsonParams;
    }


    public JSONObject sendRequest() {
        try {
            URL url = new URL(api);
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");
            con.setDoOutput(true);
            con.setDoInput(true);
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
            writer.write(jsonParams.toString());
            writer.close();

            int responseCode = con.getResponseCode();
            if  (responseCode == HttpURLConnection.HTTP_OK) {
                StringBuilder sb = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String line = "";
                while ( (line = reader.readLine()) != null ){
                    sb.append(line);
                }
                reader.close();
                Log.d("ServerResponse", new String(sb));
                return new JSONObject(new String(sb));
            } else {
                throw new UnexpectedServerException("Unexpected server exception with status code : "+responseCode);
            }
        } catch (MalformedURLException me) {
            me.printStackTrace();
            return Excpetion2JSON.getJSON(me);
        } catch(IOException ioe) {
            ioe.printStackTrace();
            return Excpetion2JSON.getJSON(ioe);
        } catch(UnexpectedServerException ue) {
            ue.printStackTrace();
            return Excpetion2JSON.getJSON(ue);
        } catch (JSONException je) {
            je.printStackTrace();
            return Excpetion2JSON.getJSON(je);
        }
    }

    public ServerRequest(String api) {
        this.api = api;
    }

}

AsyncTask :

public class SendMultipleInvitesAsyncTask extends AsyncTask<Map<String, String>, Void, JSONObject> {

    private Context context;
    JSONArray array = new JSONArray();

    public SendMultipleInvitesAsyncTask(Context context)
    {

        this.context = context;

    }

        @Override
        protected JSONObject doInBackground(Map<String, String>... params) {
            try {
                String api = context.getResources().getString(R.string.server_url) + "contactsapi/sendInvite.php";

                Map2JSON mjs = new Map2JSON();
                JSONObject jsonParams = mjs.getJSON(params[0]);
                ServerRequest request = new ServerRequest(api, jsonParams);
                return request.sendRequest();


            } catch(JSONException je) {
                return Excpetion2JSON.getJSON(je);
            }
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            super.onPostExecute(jsonObject);

            try {
                int result = jsonObject.getInt("result");
                String message = jsonObject.getString("message");
                if ( result == 1 ) {
                    Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                    //Code for having successful result for register api goes here
                } else {
                    Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                    //Code when api fails goes here
                }

            } catch(JSONException je) {
                je.printStackTrace();
                Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
}

I tried to pass the data using hash map. But it gives an error.

Error:

     <br /><b>Warning</b>:  Invalid argument supplied for foreach() in <b>/var/www/html/contactsapi/sendInvite.php</b> on line <b>30</b><br /><br /><b>Warning</b>:  Invalid argument supplied for foreach() in <b>/var/www/html/contactsapi/sendInvite.php</b> on line <b>30</b><br /><br /><b>Warning</b>:  Invalid argument supplied for foreach() in <b>/var/www/html/contactsapi/sendInvite.php</b> on line <b>30</b><br /><br /><b>Warning</b>:  Invalid argument supplied for foreach() in <b>/var/www/html/contactsapi/sendInvite.php</b> on line <b>30</b><br />[]
09-12 09:27:13.311 4177-4200/com.example.siddhi.contactsdrivers W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

Activity:

public class SendInviteActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_invite);

        HashMap<String, String> params = new HashMap<String, String>();

        params.put("date", "17/08/2016");
        params.put("invitee_no","14788452");
        params.put("status","1");
        params.put("user_id","13");

        new SendMultipleInvitesAsyncTask(SendInviteActivity.this).execute(params);
    }
}

How can I send array from an async task? Can anyone help please. Thank you..

EDIT:

Input json:

   {
"date":"17\/08\/2016",
"invitee_no":"14788452",
"status":"1",
"user_id":"13"
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度