E
E
emigrantdd2014-09-27 03:18:12
Java
emigrantdd, 2014-09-27 03:18:12

How to solve the problem of sending string to server in android?

Good day. Everything seems to be simple, there is a json string that needs to be thrown to the server, and the server does not check the correctness of the string construction or something else, just the server and just a string, but the problem is that the server for some reason always returns 0, which means that he didn't write the line. This is where you need to send a post request to
addef38885.nichost.ru/and.php?data= . This means that all the data that after = on the server will already go to a variable. My request is in a function and looks like this

static  String SendJsonViaPost(String url, String json) {
        String responseJson = "";
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        try {
            StringEntity stringEntity = new StringEntity(json);
            stringEntity.setContentType("application/json");
            post.setEntity(stringEntity);
            HttpResponse response = client.execute(post);
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line = "";
            while ((line = rd.readLine()) != null) {
                responseJson += line;
            }

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

        return responseJson;}

and this is how I call it:
SendJsonViaPost("http://addef38885.nichost.ru/and.php?data=","testing_file_1");

there is also the PHP code of the server itself.
<?php

$par = $_POST['data'];

if ( strlen($par) >=1 )
{
 $fp = fopen('data/'.date('Ymd_His').'.txt', "a"); // Открываем файл в режиме записи 

 $mytext = $par; // Исходная строка

 $test = fwrite($fp, $mytext); // Запись в файл

 if ($test) { echo '1'; } else { echo '0'; }

 fclose($fp); //Закрытие файла
}
else { echo '0'; }

?>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Skogorev, 2014-09-27
@EnterSandman

we created a couple of files for you =)
read the difference between POST and GET

_
_ _, 2014-09-27
@AMar4enko

StringEntity stringEntity = new StringEntity(json);
stringEntity.setContentType("application/json");
post.setEntity(stringEntity);

replaced by
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("data", json));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

PS I don't know anything about Java and Android.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question