How to reduce the size of a variable passed via POST by compressing it

6

My application in Android gets the String sends to the arquivo.php that processes the data.

I soon saw that I could not pass the code in base64 to arquivo.php . I need some function in java that compresses this long String and sends it with a smaller size and that arquivo.php can decompress it to its original state so I can manipulate the data.

Is there any way to do this? Reduce code by compressing it?

Follow the code I'm using.

public void postData(String html) {
    URL url = null;
    BufferedReader reader = null;
    StringBuilder stringBuilder;

    try {
        url = new URL("http://192.168.0.15/android.php");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    Uri.Builder builder = new Uri.Builder()
            .appendQueryParameter("par", html);
    String query = builder.build().getEncodedQuery();

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));

    writer.write(query);
    writer.flush();
    writer.close();
    os.close();


        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        stringBuilder = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null)
        {
            stringBuilder.append(line + "\n");
        }
        String output = stringBuilder.toString();
        Log.d("httpcliente", "BUSCANDO => [" + output + "]");
} catch (IOException e) {
    e.printStackTrace();
}


private class ParseURL extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... strings) {
        StringBuffer buffer = new StringBuffer();
        try {
            Log.d("JSwa", "Connecting to ["+strings[0]+"]");
            Document doc  = Jsoup.connect(strings[0]).get();
            Log.d("JSwa", "Connected to ["+strings[0]+"]");
            // Get document (HTML page) title
            String title = doc.title();
            Log.d("JSwA", "Title ["+title+"]");
            buffer.append("Title: " + title + "\r\n");

            // Get meta info
            Elements metaElems = doc.select("meta");
            buffer.append("META DATA\r\n");
            for (Element metaElem : metaElems) {
                String name = metaElem.attr("name");
                String content = metaElem.attr("content");
                buffer.append("name ["+name+"] - content ["+content+"] \r\n");
            }

            Elements topicList = doc.select("h2.topic");
            buffer.append("Topic list\r\n");
            for (Element topic : topicList) {
                String data = topic.text();

                buffer.append("Data [" + data + "] \r\n");
            }



            postData(doc.html());
        }
        catch(Throwable t) {
            t.printStackTrace();
        }

        return buffer.toString();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        respText.setText(s);
    }
}
    
asked by anonymous 17.06.2015 / 20:34

1 answer

6

According to @ Luídne and the @ bfavaretto error 414 only occurs when data is passed by the URL (even if POST is sent, you can still send data by GET).

  

The error 414 Too Long URI request occurs when the provided URI was too long to be processed by the server.

     

Source: link

Sending POST to a WebService

As this answer in SOen , you can do this:

//Suas variáveis POST
String urlParameters  = "param1=a&param2=b&param3=c";

//Envia usando UTF8, altere conforme a necessidade
byte[] postData       = urlParameters.getBytes(StandardCharsets.UTF_8);

//Endereço do seu servidor
String request        = "http://example.com/index.php";

int    postDataLength = postData.length;
URL    url            = new URL(request);

HttpURLConnection conn= (HttpURLConnection) url.openConnection();           

conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );

//Necessário para o envio do POST
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");

conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
   wr.write( postData );
}

Compressing string

As per the response from SOen , you can use GZIPOutputStream to compress / compress the string:

public static byte[] compress(String string) throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream(string.length());
    GZIPOutputStream gos = new GZIPOutputStream(os);
    gos.write(string.getBytes());
    gos.close();
    byte[] compressed = os.toByteArray();
    os.close();
    return compressed;
}

If you are using the method in the MainActivity.java file you will need to import to the required libraries, the MainActivity start should look something like:

package ...;

import java.lang.String;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPOutputStream;
import java.nio.charset.StandardCharsets;
import java.net.HttpURLConnection;

Use should look something like:

compress('Meu texto');

In PHP for you to unpack use gzuncompress (not tested):

Should be something like:

echo gzuncompress($_POST['data'])

If it does not work, use gzdecode

    
17.06.2015 / 20:59