2014-02-07 187 views
0

我尝试从php服务器发送文件到Andorid客户端。这是我的Java代码:将文件从php服务器发送到Android客户端

InputStream in = null; 
try { 
HttpClient httpclient = new DefaultHttpClient(); 
HttpResponse response = httpclient.execute(new HttpGet(URL)); 

in = response.getEntity().getContent(); 
} 
    catch (Exception e) { 
Log.e("[GET REQUEST]", "Network exception"); 
    } 


    String fileName = "form.xml"; 
    File destinationfile = new File(Environment.getExternalStorageDirectory() + "/ServiceHelper/" + fileName); 


BufferedOutputStream buffer = new BufferedOutputStream(new FileOutputStream(destinationfile)); 
byte byt[] = new byte[1024]; 
int i; 

for (long l = 0L; (i = in.read(byt)) != -1; l += i) { 
    buffer.write(byt, 0, i); 
} 

我不知道应该怎么看起来像在PHP服务器的一部分,发送和保存文件,例如,德克萨斯州,或XML。

我将您的任何建议

回答

0

简化的例子在正确的地方等

String fileName = "form.xml"; 
URL url = new URL("http://example.com/form.php"); 
File destinationfile = new File(Environment.getExternalStorageDirectory() + "/ServiceHelper/" + fileName); 
URLConnection connection = url.openConnection(); 
input = connection.getInputStream(); 
byte[] buffer = new byte[4096]; 
int n = - 1; 
OutputStream output = new FileOutputStream(file); 
while ((n = input.read(buffer)) != -1) 
{ 
    output.write(buffer, 0, n); 
} 
output.close(); 

//Refresh file location MediaScannerConnection 
if (destinationfile != null) { 
    MediaScannerConnection.scanFile(context, new String[] { destinationfile.toString() }, null, null); 
} 

在PHP从w3schools加试捕非常感谢:

form.php

<?php 
header("Content-type: text/xml"); 
echo "<?xml version='1.0' encoding='UTF-8'?>"; 
echo "<note>"; 
echo "<from>Jani</from>"; 
echo "<to>Tove</to>"; 
echo "<message>Remember me this weekend</message>"; 
echo "</note>"; 
?> 
相关问题