Android - 如果设备从USB电缆拔出,HttpClient会响应连接超时

时间:2018-01-26 17:25:13

标签: java android httpclient device

当我从PC上拔下我的Android设备时,我从HttpResponse收到连接超时。 当设备使用usb线连接到PC时,设备拔出时代码工作正常有错误

连接到网址:80 [url / ip]失败:连接超时

所有权限访问权限。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

代码:

public static void transferFilePost(String fileDir, String fileName) throws IOException {
        String filePath = fileDir + fileName;
        final File myFile = new File(filePath);
        if (myFile.exists())
            System.out.println("File Exists>>>>>>>>>>>>>>>>=" + myFile);
        else
            return;

        appendLog("transferFilePost 1");

        RandomAccessFile f = new RandomAccessFile(filePath, "r");
        byte[] b = new byte[(int) f.length()];
        f.readFully(b);
        String str = Base64.encodeToString(b, Base64.DEFAULT);

        appendLog("transferFilePost 2");

        String url = "http://myurl";
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);

        appendLog("transferFilePost 3");

        post.setHeader("User-Agent", USER_AGENT);

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("fileName", fileName));
        urlParameters.add(new BasicNameValuePair("f", str));

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        appendLog("transferFilePost 4");

        HttpResponse response = client.execute(post);

        appendLog("transferFilePost 5");

        System.out.println("response>>>>>>>>>>>>>>>>=" + response.getStatusLine().getStatusCode());

        appendLog("response>>>>>>>>>>>>>>>>=" + response.getStatusLine().getStatusCode());

        if (response.getStatusLine().getStatusCode() == 200)
            myFile.delete();
    }

可能是什么原因?请帮忙......

0 个答案:

没有答案