Moynul
Moynul

Reputation: 635

Send json string to server

My client type is android and the language is Java.

This class connects to the server and gets the output stream to the connected server.

class ConnectToServer extends AsyncTask<Void, Void, Void>
{

    @Override
    protected Void doInBackground(Void... params)
    {
        try {
            socket = new Socket(ip,port);
            output = new DataOutputStream(socket.getOutputStream());
            Log.d(TAG, "Connected To Server!");

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}

class SendToServer extends AsyncTask<Void, Void, Void>
{
    //Our Json object
    JSONObject obj;// = new JSONObject();

    //this class is called when the login button is pressed, it sends the username and password as arguments
    public SendToServer(String username, String password)
    {
        //instantiate the new object
        obj = new JSONObject();

        try {
            //create the first field Type
            obj.put("Type", new Integer(1)); //Type is something our Server will switch against-Type 1 = login request
            obj.put("username", username);  //our server will get username
            obj.put("password",password);   //our server will get password
        } catch (JSONException e) {
            e.printStackTrace();        //if we get problems let the developer know
        }
    }
    @Override
    protected Void doInBackground(Void... params)
    {
        String jsonText = obj.toString();                       //convert our json object into a string
        byte[] b =jsonText.getBytes(Charset.forName("UTF-8"));  //convert our json object into a byte array
        try {
            output.writeInt(b.length); // write length of the message
            output.write(b);           // write the message
            output.flush();            //flush - empties the pipe
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}

}

The purpose of this code is to send the server the users credentials.

In this C# Server

    private void serverClient()
    {
        while(true)
        {
            int len = ns.ReadByte(); //read how much data

            if (len == 0)   //if this == 0 this means client has quit the program
                break;      //break out of loop and remove client from array list 

            if (len > 0)    //we have a message 
            {
                //read mess
                byte[] message = new byte[len];         //create byte array 
                ns.Read(message, 0, message.Length);    //read into the message byte array
                string text = Encoding.ASCII.GetString(message, 0, len);
                string text1 = Encoding.UTF8.GetString(message, 0, len);    //build string from byte array up to how much data we got. 

                Console.WriteLine(text1);
            }
        }

        removeClients();

    }

So the Android client will send the credentials, but when the SendToServer class is called, the client disconnects from the server.

How can I send a Json string to my C# server so it can then read the string and serialize it into an object, depending on the fields.

Upvotes: 1

Views: 1674

Answers (2)

Nguyễn Trung Hiếu
Nguyễn Trung Hiếu

Reputation: 2032

You're reading lines but you aren't writing lines. Add a line terminator to the message being sent, or use println() instead of write().

Upvotes: 0

Nguyễn Trung Hiếu
Nguyễn Trung Hiếu

Reputation: 2032

private void updateDataToServer() {

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("name", name));
    nameValuePairs.add(new BasicNameValuePair("score", score));

    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url_update);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.e("pass 1", "connection success ");
    } catch (Exception e) {
        Log.e("Fail 1", e.toString());
        Toast.makeText(getApplicationContext(), "Invalid IP Address", Toast.LENGTH_LONG).show();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
        Log.e("pass 2", "connection success ");
    } catch (Exception e) {
        Log.e("Fail 2", e.toString());
    }

    try {
        JSONObject json_data = new JSONObject(result);
        code = (json_data.getInt("code"));

        if (code == 1) {
            /*
             * Toast.makeText(getBaseContext(), "Update Successfully",
             * Toast.LENGTH_SHORT).show();
             */
        } else {
            Toast.makeText(getBaseContext(), "Sorry, Try Again", Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Log.e("Fail 3", e.toString());
    }

}

class PostDataToServer extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        /*
         * pDialog = new ProgressDialog(MainActivity.this);
         * pDialog.setMessage("Please wait..."); pDialog.show();
         */
    }

    @Override
    protected String doInBackground(String... params) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url_create_product);

        try {
            name = edt_name.getText().toString();
            score = edt_score.getText().toString();
            quocgia = edt_quocgia.getText().toString();
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("name", name));
            nameValuePairs.add(new BasicNameValuePair("score", score));
            nameValuePairs.add(new BasicNameValuePair("quocgia", quocgia));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        /*
         * if (pDialog.isShowing()) { pDialog.dismiss();
         * Toast.makeText(getApplication(), "Complete",
         * Toast.LENGTH_LONG).show(); }
         */
    }
}

Hope it helps you

Upvotes: 1

Related Questions