【问题标题】:How can I make an Android app communicate with a web server over the internet?如何使 Android 应用程序通过 Internet 与 Web 服务器通信?
【发布时间】:2012-03-19 01:58:33
【问题描述】:
我有一个应用程序的想法,目前正在学习 Android 开发。我非常熟悉创建简单的独立应用程序。
我也熟悉 PHP 和虚拟主机。
我想要做的是,让一个 android 应用程序通过互联网将图像发送到服务器并让服务器返回处理后的图像。我不知道该怎么做。
您能否告诉我如何才能实现这一目标,或者我应该研究哪些主题?另外,我可以使用哪些脚本在 Web 服务器上进行处理?特别是,我可以使用 PHP 或 Java 吗?
谢谢!
【问题讨论】:
标签:
php
android
web-services
http
webserver
【解决方案1】:
For Image Uploading
///Method Communicate with webservice an return Yes if Image uploaded else NO
String executeMultipartPost(Bitmap bm,String image_name) {
String resp = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("domain.com/upload_image.php");
ByteArrayBody bab = new ByteArrayBody(data, image_name);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploaded", bab);
reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
resp=s.toString();
} catch (Exception e) {
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
}
return resp;
}
//PHP Code
<?php
$target = "upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "yes";
}
else {
echo "no";
}
?>
【解决方案2】:
通常我们使用http连接,你可以在
发布参数,更多参考请参阅link
【解决方案3】:
您必须创建一个简单的 php web 服务,它接受参数作为图像字节并处理图像并存储在服务器中。对于这个 android 应用程序将使用 HttpPost 以字节为单位向服务器发送图像数据。
出于检索目的,您必须创建一个其他 Web 服务,该服务将输出图像的文件名,android 应用程序可以从中检索图像