Android应用程序使用php传输字符串到服务器


Android app transfers string to server using php

在我的项目中,我需要将图像和字符串传输到服务器(服务器端使用php)。我完成了上传图片到服务器。唯一的问题是如何将字符串发送到服务器。有人能告诉我怎么做吗?

这里有一些代码可以为您指明正确的方向。

首先,在应用程序端使用如下代码:

Java:

// generate your params:
String yourString = "This is the string you want to send";
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("your_string", yourString));
// send them on their way
try {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("http://xyz/your_php_script.php");
    httpPost.setEntity(new UrlEncodedFormEntity(nameValueParams));  
    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();   
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

然后在你的服务器端(http://xyz/your_php_script.php):

)PHP:

<?php
    if (isset($_POST['your_string']) && $_POST['your_string'] != '') {
        $your_string = $_POST['your_string'];
        echo 'received the string: ' . $your_string;
    } else {
        echo 'empty';
    }
?>

编辑,根据你的评论:

它更复杂,因为你必须使用OutputStreamBufferedWriter,所以我不知道为什么我的解决方案对你不起作用。通过谷歌,我找到了以下可能对你有帮助的答案:

  • https://stackoverflow.com/a/13486223/586859
  • Android HTTPUrlConnection POST
  • http://digitallibraryworld.com/?p=189