Answer the question
In order to leave comments, you need to log in
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;}
SendJsonViaPost("http://addef38885.nichost.ru/and.php?data=","testing_file_1");
<?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
we created a couple of files for you =)
read the difference between POST and GET
StringEntity stringEntity = new StringEntity(json);
stringEntity.setContentType("application/json");
post.setEntity(stringEntity);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("data", json));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question