如何使一个Android应用程序能够通过互联网与web服务器进行通信?

4
我有一个应用程序的想法,目前正在学习Android开发。我相当熟悉创建简单的独立应用程序。
我也熟悉PHP和Web托管。
我的想法是,制作一个Android应用程序通过互联网将图像发送到服务器,并使服务器返回处理后的图像。我不知道如何做到这一点。
请问我该如何实现这个功能或者我应该学习哪些主题?还有,在Web服务器上可以使用哪些脚本来进行处理?特别是,我可以使用PHP或Java吗?
谢谢!
3个回答

6
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";
    }
?> 

1
通常我们使用http连接来完成这个操作,您可以将图像传递给post参数,更多信息请参见link

0

您需要创建一个简单的PHP Web服务,接受图像字节作为参数,并处理图像并存储在服务器上。为此,Android应用程序将使用HttpPost将图像数据以字节形式发送到服务器。

为了检索目的,您需要创建另一个Web服务,它将输出图像文件的文件名,从中Android应用程序可以检索图像。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接