通过套接字连接传递特殊字符

时间:2015-08-03 23:08:20

标签: android sockets special-characters

我在Android中使用套接字构建了一个聊天应用程序。只要用户不发送带有特殊字符的消息,即消息发送和接收都很好。 Hey, it's me,将无效,但Hey its me,逗号和撇号会阻止邮件传递。

我尝试使用URLEncoder,但不允许发送唯一字符。

发送消息方法:

  public String sendMessage(String username, String tousername, String message, String campaign_id, String location_id)
            throws UnsupportedEncodingException {
        String params = "username=" + URLEncoder.encode(this.username, "UTF-8")
                + "&password=" + URLEncoder.encode(this.password, "UTF-8")
                + "&to=" + URLEncoder.encode(tousername, "UTF-8")
                + "&message=" + URLEncoder.encode(message, "UTF-8")
                + "&campaign_id=" + URLEncoder.encode(campaign_id, "UTF-8")
                + "&location_id=" + URLEncoder.encode(location_id, "UTF-8")
                + "&action=" + URLEncoder.encode("sendMessage", "UTF-8")
                + "&gcmregid=" + gcmRegistrationID
                + "&";
        Log.i("PARAMS", params);
        return socketOperator.sendHttpRequest(params);
    }

SocketerInterface socketOperator = new Socketer(this);

和Socketer课程:

public class Socketer implements SocketerInterface {
    // Have to set the proper ports that apache is runnign on as well as your
    // computers IP address: ie. ip:4430 or 800
    Global ipAddress = new Global();
    private final String AUTHENTICATION_SERVER_ADDRESS = "http://"
             // + ipAddress.getIpAddress() + ":80/AndroidChatterDatabase/";   // Google Compute Engine Access
            //+ ipAddress.getIpAddress() + ":4430/AndroidChatterDatabase/"; // Localhost access

              + ipAddress.getFeastChatServer(); // For Heroku access

    private int listeningPort = 0;

    private static final String HTTP_REQUEST_FAILED = null;

    private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();

    private ServerSocket serverSocket = null;

    private boolean listening;

    private class ReceiveConnection extends Thread {
        Socket clientSocket = null;

        public ReceiveConnection(Socket socket) {
            this.clientSocket = socket;
            Socketer.this.sockets.put(socket.getInetAddress(), socket);
        }

        @Override
        public void run() {
            try {
                // PrintWriter out = new
                // PrintWriter(clientSocket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        clientSocket.getInputStream()));
                String inputLine;

                while ((inputLine = in.readLine()) != null) {
                    Log.v("XML MESSAGE", inputLine);

                    if (inputLine.equals("exit") == false) {// as long as have
                                                            // noted exited yet,
                                                            // will continuing
                                                            // reading in


                        Log.v("XML MESSAGE", inputLine);
                        // appManager.messageReceived(inputLine);
                    } else {
                        clientSocket.shutdownInput();
                        clientSocket.shutdownOutput();
                        clientSocket.close();
                        Socketer.this.sockets.remove(clientSocket
                                .getInetAddress());
                    }
                }

            } catch (IOException e) {
                Log.e("ReceiveConnection.run: when receiving connection ", "");
            }
        }
    }

    public Socketer(Manager appManager) {
    }

    public String sendHttpRequest(String params) {
        URL url;
        String result = new String();
        try {
            url = new URL(AUTHENTICATION_SERVER_ADDRESS);
            HttpURLConnection connection;
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);

            PrintWriter out = new PrintWriter(connection.getOutputStream());

            out.println(params);
            out.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                result = result.concat(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (result.length() == 0) {
            result = HTTP_REQUEST_FAILED;
        }

        // This is the output of the datastream from the server ie. <data>
        // (bunch of data...etc) </data>

        // Testing to remove <head/> tag from Google App Engine
        //return result.replace("<head/>","");
        return result;

    }

    public int startListening(int portNo) {
        listening = true;

        try {
            serverSocket = new ServerSocket(portNo);
            this.listeningPort = portNo;
        } catch (IOException e) {

            // e.printStackTrace();
            this.listeningPort = 0;
            return 0;
        }

        while (listening) {
            try {
                new ReceiveConnection(serverSocket.accept()).start();

            } catch (IOException e) {
                // e.printStackTrace();
                return 2;
            }
        }

        try {
            serverSocket.close();
        } catch (IOException e) {
            Log.e("Exception server socket",
                    "Exception when closing server socket");
            return 3;
        }

        return 1;
    }

    public void stopListening() {
        this.listening = false;
    }

    public void exit() {
        for (Iterator<Socket> iterator = sockets.values().iterator(); iterator
                .hasNext();) {
            Socket socket = (Socket) iterator.next();
            try {
                socket.shutdownInput();
                socket.shutdownOutput();
                socket.close();
            } catch (IOException e) {
            }
        }
        sockets.clear();
        this.stopListening();
    }

    public int getListeningPort() {

        return this.listeningPort;
    }

}

如何格式化/编码以允许发送这些消息?

1 个答案:

答案 0 :(得分:0)

Java使用UTF-16进行内部字符串表示,但看起来您使用的是UTF-8,但是当从BufferedReader读取UTF-8时,您没有做任何特殊的转换。在参数中,请尝试指定UTF-16。

来自Java String documentation

  

String表示UTF-16格式的字符串