Android应用程序使用php将字符串传输到服务器
在我的项目中,我需要将图像和字符串传输到服务器(服务器端使用php)。我完成了将图像上传到服务器的工作。因此,唯一的问题是如何将字符串发送到服务器。有人能告诉我怎么做吗?以下是一些代码,可以为您指明正确的方向 首先,在您的应用程序端使用如下内容: Java:Android应用程序使用php将字符串传输到服务器,php,android,Php,Android,在我的项目中,我需要将图像和字符串传输到服务器(服务器端使用php)。我完成了将图像上传到服务器的工作。因此,唯一的问题是如何将字符串发送到服务器。有人能告诉我怎么做吗?以下是一些代码,可以为您指明正确的方向 首先,在您的应用程序端使用如下内容: Java: // generate your params: String yourString = "This is the string you want to send"; List<NameValuePair> nameValueP
// 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();
}
<?php
if (isset($_POST['your_string']) && $_POST['your_string'] != '') {
$your_string = $_POST['your_string'];
echo 'received the string: ' . $your_string;
} else {
echo 'empty';
}
?>
//生成您的参数:
String yourString=“这是您要发送的字符串”;
List nameValuePairs=新的ArrayList();
添加(新的BasicNameValuePair(“您的字符串”,yourString));
//让他们上路
试一试{
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://xyz/your_php_script.php");
setEntity(新的UrlEncodedFormEntity(nameValueParams));
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
在您的服务器端()上使用类似这样的内容来获取它:
PHP:
// 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();
}
<?php
if (isset($_POST['your_string']) && $_POST['your_string'] != '') {
$your_string = $_POST['your_string'];
echo 'received the string: ' . $your_string;
} else {
echo 'empty';
}
?>
根据您的评论编辑:
它更复杂,因为您必须使用OutputStream
和BufferedWriter
,所以我不知道为什么我的解决方案不适合您。使用谷歌,我发现以下答案可能对你有所帮助: