Java 将文件从php服务器发送到Android客户端
我尝试将文件从php服务器发送到AndroID客户端。这是我的java代码:Java 将文件从php服务器发送到Android客户端,java,php,android,file,Java,Php,Android,File,我尝试将文件从php服务器发送到AndroID客户端。这是我的java代码: InputStream in = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(new HttpGet(URL)); in = response.getEntity().getContent(); } catch (Exception e) { Lo
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中,发送和保存文件(例如tx或xml)应该是服务器的一部分
如果您有任何建议,我将不胜感激。在正确的位置添加简化示例、添加try catch等
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中来自:
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>";
?>