用于传输数据的Android应用

时间:2017-06-20 02:56:24

标签: java android websocket httpurlconnection

我通过HTTPUrlConnection向服务器发送数据。它在服务器端通过PHP代码接收并插入MySQL数据库。一切都按预期运作。问题是它使用了大量数据来完成它。我发送的信息位于变量unitData中,长度介于80到200个字符之间。据报道,每次转移使用的数据为3K到8K。移动200字节似乎需要很多开销。我需要这个尽可能小,以便我的应用程序工作,最好是500字节以下。有没有办法调整HTTPUrlConnection或者我应该完全使用Websockets还是其他东西?

class dataSender extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        String unitData = params[0];
        try {
            URL url = new URL("https://www.website.php");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setReadTimeout(10000);
            connection.setConnectTimeout(10000);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

            //connection.setRequestProperty("Content-Length", "" + test.length());
            connection.setRequestProperty("Content-Language", "en-US");

            connection.setUseCaches (false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());

            wr.writeBytes ("mydata="+unitData);
            wr.flush ();
            wr.close ();

            //Get Response
            int responseCode = connection.getResponseCode();
            StringBuffer response = new StringBuffer();
            if(responseCode == 200) {
                InputStream is = connection.getInputStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(is));
                String line;

                while ((line = rd.readLine()) != null) {
                    response.append(line);
                    response.append('\r');
                }
                rd.close();
            }
            else{
                response.append("Error:");
                response.append(responseCode);
            }

            connection.disconnect();

            return response.toString();
            //return "nada";

        } catch (Exception e) {
            //Toast.makeText(getApplicationContext(), "exception:"+e, Toast.LENGTH_SHORT);

            return e.toString();
        }

    }
}

0 个答案:

没有答案