繁体   English   中英

将json字符串发送到服务器

[英]Send json string to server

我的客户端类型是 android,语言是 Java。

此类连接到服务器并将输出流获取到连接的服务器。

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;
    }
}

}

此代码的目的是向服务器发送用户凭据。

在这个 C# 服务器中

    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();

    }

所以 Android 客户端会发送凭证,但是当调用SendToServer类时,客户端会断开与服务器的连接。

如何将 Json 字符串发送到我的 C# 服务器,以便它可以读取字符串并将其序列化为对象,具体取决于字段。

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(); }
         */
    }
}

希望对你有帮助

你在读台词,但不是在写台词。 向正在发送的消息添加行终止符,或使用 println() 而不是 write()。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM