拒绝连接到Apache服务器
问题描述:
我知道在*上有类似的问题,但他们没有解决我的问题。我想从android上传一个文件到本地的apache服务器,但是获得了'连接被拒绝'的错误。拒绝连接到Apache服务器
我在Mac OS X Lion(Port 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
答
该代码似乎没问题。仿真器可以无问题地连接。路由器防火墙出现问题
答
你有防火墙的启用和你的Mac上运行?
确定端口80是否真正打开的最佳方式(IMHO)是在本地网络上的另一台计算机上针对目标地址运行NMap(或gui Zenmap)。
如果只是您的台式机和您的Android设备,您可以尝试浏览http://192.168.x.x以查看Apache服务器是否提供响应。
端口已打开。它是由路由器防火墙引起的。谢谢 – 2012-07-26 06:55:08