我知道 Stackoverflow 上有类似的问题,但它们并没有解决我的问题。我想将文件从 android 上传到本地 apache 服务器,但出现“连接被拒绝”错误。
我在 Mac OS X Lion(端口 80 上的 Apache)上使用带有 Android 3.2 和 MAMP 的物理设备。我还在清单中添加了 INTERNET 权限。
这是代码:
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(new File(
"/mnt/sdcard/somefile.xml"));
} catch (FileNotFoundException e) {
...
}
URL url = null;
try {
url = new URL("http://192.168.x.xxx:80/index.php");
} catch (MalformedURLException e) {
...
}
try {
// Open a HTTP connection to the URL
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
+ SOMEFILE + "" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1000;
// int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bytesAvailable];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
while (bytesRead > 0) {
dos.write(buffer, 0, bytesAvailable);
bytesAvailable = fileInputStream.available();
bytesAvailable = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
fileInputStream.close();
dos.flush();
dos.close();
} catch (IOException e) {
...
}
例外:
07-24 14:48:43.280: E/App(5802): failed to upload file '/mnt/sdcard/somefile.xml' to
server 'http://192.168.x.xxx:80/index.php'
07-24 14:48:43.280: E/App(5802): java.net.ConnectException: /192.168.x.xxx:80 -
Connection refused