Java org.apache.http.conn.ConnectTimeoutException 代码实例

・66 分钟阅读

以下是展示如何使用org.apache.http.conn.ConnectTimeoutException的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


public Socket connectSocket(
        final Socket socket,
        final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress,
        final HttpParams params)
            throws IOException, UnknownHostException, ConnectTimeoutException {
    if (remoteAddress == null) {
        throw new IllegalArgumentException("Remote address may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    Socket sock;
    if (socket != null) {
        sock = socket;
    } else {
        sock = createSocket(params);
    }
    if (localAddress != null) {
        sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        sock.bind(localAddress);
    }
    int timeout = HttpConnectionParams.getConnectionTimeout(params);
    try {
        sock.connect(remoteAddress, timeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"
                + remoteAddress.getAddress() + " timed out");
    }
    return sock;
}
 

实例 2


public Socket connectSocket(
        final Socket socket,
        final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress,
        final HttpParams params)
            throws IOException, UnknownHostException, ConnectTimeoutException {
    if (remoteAddress == null) {
        throw new IllegalArgumentException("Remote address may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    Socket sock;
    if (socket != null) {
        sock = socket;
    } else {
        sock = createSocket(params);
    }
    if (localAddress != null) {
        sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        sock.bind(localAddress);
    }
    int timeout = HttpConnectionParams.getConnectionTimeout(params);
    try {
        sock.connect(remoteAddress, timeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"
                + remoteAddress.getAddress() + " timed out");
    }
    return sock;
}
 

实例 3


@Override
public Socket connectSocket(Socket sock, String host, int port,
                InetAddress localAddress, int localPort, HttpParams params) throws IOException,
                UnknownHostException, ConnectTimeoutException {
        if (host == null) {
           throw new IllegalArgumentException("Target host may not be null.");
       }
       if (params == null) {
           throw new IllegalArgumentException("Parameters may not be null.");
       }
       if (sock == null)
           sock = createSocket();
       if ((localAddress != null) || (localPort > 0)) {
           // we need to bind explicitly
           if (localPort < 0)
               localPort = 0; // indicates "any"
           InetSocketAddress isa =
               new InetSocketAddress(localAddress, localPort);
           sock.bind(isa);
       }
       return new SocksSocket(sProxy,host, port);
}
 

实例 4


/**
 * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket, java.lang.String, int,
 *      java.net.InetAddress, int, org.apache.http.params.HttpParams)
 */
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort,
                HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
        int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
        int soTimeout = HttpConnectionParams.getSoTimeout(params);
        InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
        SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
        if ((localAddress != null) || (localPort > 0)) {
                // we need to bind explicitly
                if (localPort < 0) {
                        localPort = 0; // indicates "any"
                }
                InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
                sslsock.bind(isa);
        }
        sslsock.connect(remoteAddress, connTimeout);
        sslsock.setSoTimeout(soTimeout);
        return sslsock;
}
 

实例 5


public Socket connectSocket(Socket sock, String host, int port,
                InetAddress localAddress, int localPort, HttpParams params)
                throws IOException, UnknownHostException, ConnectTimeoutException {
        int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
        int soTimeout = HttpConnectionParams.getSoTimeout(params);
        InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
        SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
        if ((localAddress != null) || (localPort > 0)) {
                // we need to bind explicitly
                if (localPort < 0) {
                        localPort = 0; // indicates "any"
                }
                InetSocketAddress isa = new InetSocketAddress(localAddress,
                                localPort);
                sslsock.bind(isa);
        }
        sslsock.connect(remoteAddress, connTimeout);
        sslsock.setSoTimeout(soTimeout);
        return sslsock;
}
 

实例 6


public Socket connectSocket(
        final Socket socket,
        final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress,
        final HttpParams params)
            throws IOException, UnknownHostException, ConnectTimeoutException {
    if (remoteAddress == null) {
        throw new IllegalArgumentException("Remote address may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    Socket sock;
    if (socket != null) {
        sock = socket;
    } else {
        sock = createSocket(params);
    }
    if (localAddress != null) {
        sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        sock.bind(localAddress);
    }
    int timeout = HttpConnectionParams.getConnectionTimeout(params);
    try {
        sock.connect(remoteAddress, timeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"
                + remoteAddress.getAddress() + " timed out");
    }
    return sock;
}
 

实例 7


@Override
public Document downloadXML(String url, String[] keys, String[] values, HTTP_CALLING_METHOD callingMethod) throws GeneralException {
        if(!NetworkConnective.checkNetwork(this.application))
        {
                throw this.makeGeneralNoNetworkGeneralException();
        }
        try {
                if(callingMethod != null)
                {
                        if(callingMethod.equals(HTTP_CALLING_METHOD.POST))
                        {
                                byte[] byteArray = HttpUtil.downloadXMLFromPost(url, keys, values);
                                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
                                Document document = XMLUtil.toDocument(byteArrayInputStream);
                                return document;
                        }
                        else if(callingMethod.equals(HTTP_CALLING_METHOD.GET))
                        {
                                byte[] byteArray = HttpUtil.downloadXMLFromGet(url, keys, values);
                                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
                                Document document = XMLUtil.toDocument(byteArrayInputStream);
                                return document;
                        }
                }
                byte[] byteArray = HttpUtil.downloadXMLFromPost(url, keys, values);
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
                Document document = XMLUtil.toDocument(byteArrayInputStream);
                if(document != null)
                {
                        if(document.getDocumentElement() != null)
                        {
                                document.getDocumentElement().normalize();
                        }                               
                }
                return document;
        } catch (ConnectTimeoutException e) {
                LogController.log("HttpConnectionManager downloadXML ConnectTimeoutException " + e);
                throw makeGeneralException();
        }
        catch (ClientProtocolException e)
        {
                LogController.log("HttpConnectionManager downloadXML ClientProtocolException " + e);
                throw makeGeneralException();
        }
        catch (Exception e)
        {
                LogController.log("HttpConnectionManager downloadXML Exception " + e);
                e.printStackTrace();
                throw makeGeneralException();
        }
}
 

实例 8


@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = new HashMap<String, String>();
        try {
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // Handle cache validation.
            if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry() == null
                        ? null
                        : request.getCacheEntry().data, responseHeaders, true);
            }
            // Some responses such as 204s do not have content. We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity());
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }
            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, statusLine);
            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false);
                if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(networkResponse);
            }
        }
    }
}
 

实例 9


@Override
public void run() {
        HttpRequestBase httpRequest = null;
        int customResultCode = RequestReceiver.RESULT_STATE_NETWORK_ERROR;
        int statusCode = -1;
        try {
                if (rEntity.getMethod() == RequestMethod.GET) {
                        httpRequest = new HttpGet(rEntity.getUrl());
                } else {
                        // POST/POST_WITH_FILE
                        HttpPost httpPost = new HttpPost(rEntity.getUrl());
                        // ???????
                        httpPost.setEntity(rEntity.getPostEntitiy());
                        httpRequest = httpPost;
                }
                HttpConnectionParams.setSoTimeout(httpRequest.getParams(),
                                CONNECTION_TIMEOUT);
                //
                HttpResponse response = httpClient.execute(httpRequest);
                statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                        rEntity.setRawResponse(EntityUtils.toString(
                                        response.getEntity(), rEntity.getCurrentCharset()));
                        customResultCode = RequestReceiver.RESULT_STATE_OK;
                } else {
                        customResultCode = RequestReceiver.RESULT_STATE_NETWORK_ERROR;
                }
        } catch (ConnectTimeoutException e) {
                e.printStackTrace();
                customResultCode = RequestReceiver.RESULT_STATE_TIME_OUT;
        } catch (ClientProtocolException e) {
                e.printStackTrace();
                customResultCode = RequestReceiver.RESULT_STATE_NETWORK_ERROR;
        } catch (Exception e) {
                e.printStackTrace();
                customResultCode = RequestReceiver.RESULT_STATE_NETWORK_ERROR;
        } finally {
                try {
                        httpRequest.abort();
                } catch (Exception e) {
                        // ignore
                }
        }
        // Debug
        if (DEBUG) {
                reportRequestEntity(rEntity, statusCode);
        }
        RequestReceiver rr = rEntity.getRequestReceiver();
        if (rr instanceof ParasiticRequestReceiver) {
                ((ParasiticRequestReceiver) rr).parasiticHandler(
                                rEntity.getResultCode(), rEntity.getRequestId(),
                                rEntity.getTag(), rEntity.getRawResponse());
        }
        synchronized (this) {
                if (!isInterrupted) {
                        synchronized (rEntity) {
                                if (rEntity.isCanceled()) {
                                        tryNotifyCanceled(rEntity);
                                } else {
                                        // ??????
                                        rEntity.setResultCode(customResultCode);
                                        Message msg = httpHandler.obtainMessage();
                                        msg.obj = rEntity;
                                        httpHandler.sendMessage(msg);
                                }
                        }
                }
        }
        recycle();
}
 

实例 10


/**
 * ???qq??
 *
 * @param context
 * @param title   feeds???
 * @param url     ?????????????????????????????????2???????http://???
 * @param comment ?????????????????????????????1???????????????????40?????
 *                ?????????
 * @param summary ??????????????????????????????????3???80??????????????
 */
public static void addShare(final Context context, String title,
                            String url, String comment, String summary, String imageUrl, String site, String fromUrl,
                            final UniversalCallBack callBack) {
    if (ready(context)) {
        Bundle paramas = new Bundle();
        paramas.putString("title", title);// ???feeds??????36??????????????
        paramas.putString("url", url);// ?????????????????????????????http://???
        paramas.putString("comment", comment);// ??????????????????????????????????????40??????????????
        paramas.putString("summary", summary);// ???????????????????????????80??????????????
        if (!TextUtils.isEmpty(imageUrl)) {
            // ????????????????"???http://???????255???????????|????????????????????100*100???
            paramas.putString("images", imageUrl);
        }
        paramas.putString("type", "4");// ????????
        paramas.putString("site", site);// ????????
        paramas.putString("fromurl", fromUrl);// ????????
        paramas.putString("nswb", "1");// ????????
        getTencent(context).requestAsync(Constants.GRAPH_ADD_SHARE,
                paramas, Constants.HTTP_POST, new IRequestListener() {
                    @Override
                    public void onUnknowException(Exception arg0,
                                                  Object arg1) {
                        callBack.onFaild();
                    }
                    @Override
                    public void onSocketTimeoutException(
                            SocketTimeoutException arg0, Object arg1) {
                        callBack.onFaild();
                    }
                    @Override
                    public void onNetworkUnavailableException(
                            NetworkUnavailableException arg0, Object arg1) {
                        callBack.onFaild();
                    }
                    @Override
                    public void onMalformedURLException(
                            MalformedURLException arg0, Object arg1) {
                        callBack.onFaild();
                    }
                    @Override
                    public void onJSONException(JSONException arg0,
                                                Object arg1) {
                        callBack.onFaild();
                    }
                    @Override
                    public void onIOException(IOException arg0, Object arg1) {
                        callBack.onFaild();
                    }
                    @Override
                    public void onHttpStatusException(
                            HttpStatusException arg0, Object arg1) {
                        callBack.onFaild();
                    }
                    @Override
                    public void onConnectTimeoutException(
                            ConnectTimeoutException arg0, Object arg1) {
                        callBack.onFaild();
                    }
                    @Override
                    public void onComplete(JSONObject arg0, Object arg1) {
                        callBack.onSuccess();
                    }
                }, null);
    }
}
 

实例 11


@Override
protected ArrayList<Bulb> doInBackground(Void... arg0) {
        try {
                HttpParams httpParameters = new BasicHttpParams();
                int timeoutConnection = 5000;
                HttpConnectionParams.setConnectionTimeout(httpParameters,
                                timeoutConnection);
                int timeoutSocket = 5000;
                HttpConnectionParams
                                .setSoTimeout(httpParameters, timeoutSocket);
                HttpClient client = new DefaultHttpClient(httpParameters);
                String getURL = "http://" + b.getInternalipaddress() + "/api/"
                                + userName + "/lights";
                HttpGet get = new HttpGet(getURL);
                HttpResponse responseGet = client.execute(get);
                HttpEntity resEntityGet = responseGet.getEntity();
                if (resEntityGet != null) {
                        InputStream is = resEntityGet.getContent();
                        BufferedReader reader = new BufferedReader(
                                        new InputStreamReader(is, "UTF-8"), 8);
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                                sb.append(line + "n");
                        }
                        is.close();
                        if (!sb.toString().contains("unauthorized user")) {
                                JSONObject json = new JSONObject(sb.toString());
                                Iterator<?> keys = json.keys();
                                ArrayList<Bulb> bulbs = new ArrayList<Bulb>();
                                while (keys.hasNext()) {
                                        String key = (String) keys.next();
                                        if (json.get(key) instanceof JSONObject) {
                                                Bulb b = new Bulb();
                                                JSONObject obj = (JSONObject) json.get(key);
                                                b.setName(obj.getString("name"));
                                                b.setNumber(key);
                                                b.setRawJSON(obj);
                                                DefaultHttpClient defaulthttpclient = new DefaultHttpClient();
                                                HttpGet httpget = new HttpGet("http://"
                                                                + bridge.getInternalipaddress()
                                                                + "/api/" + userName + "/lights/"
                                                                + b.getNumber());
                                                HttpResponse httpresponse = defaulthttpclient
                                                                .execute(httpget);
                                                BufferedReader bufferedreader;
                                                bufferedreader = new BufferedReader(
                                                                new InputStreamReader(httpresponse
                                                                                .getEntity().getContent()));
                                                String content = bufferedreader.readLine();
                                                Gson g = new Gson();
                                                BulbState state = g.fromJson(content,
                                                                BulbState.class);
                                                b.setState(state);
                                                bulbs.add(b);
                                        }
                                }
                                progress_dialog.cancel();
                                new PreferencesManager(act).storeBulbs(bulbs);
                                listener.onLightsScanCompletedSuccessfully(bulbs);
                                return bulbs;
                        } else {
                                progress_dialog.cancel();
                                listener.onLightsScanCompletedUnsuccessfully(
                                                "Unauthorized user. Have you got a response from registerWithBridge yet?",
                                                false);
                        }
                }
        } catch (HttpHostConnectException e) {
                e.printStackTrace();
                progress_dialog.cancel();
                if (Utils.isWifiConnected(act)) {
                        listener.onLightsScanCompletedUnsuccessfully(
                                        "Unable to find bridge. Perhaps it has moved?",
                                        true);
                } else {
                        listener.onWifiNotAvailable();
                }
        } catch (ConnectTimeoutException e) {
                e.printStackTrace();
                progress_dialog.cancel();
                if (Utils.isWifiConnected(act)) {
                        listener.onLightsScanCompletedUnsuccessfully(
                                        "Unable to find bridge. Perhaps it has moved?",
                                        true);
                } else {
                        listener.onWifiNotAvailable();
                }
        } catch (Exception e) {
                e.printStackTrace();
                progress_dialog.cancel();
                listener.onLightsScanCompletedUnsuccessfully(
                                "Unknown error, unable to complete scan.", false);
        }
        return null;
}
 

实例 12


/**
 * Uploads to urlString the submission identified by id with filepath of instance 
 * @param urlString destination URL
 * @param id 
 * @param instanceFilePath 
 * @param toUpdate - Instance URL for recording status update.
 * @param httpclient - client connection
 * @param localContext - context (e.g., credentials, cookies) for client connection
 * @param uriRemap - mapping of Uris to avoid redirects on subsequent invocations
 * @return false if credentials are required and we should terminate immediately.
 */
private boolean uploadOneSubmission(String urlString, String id, String instanceFilePath, 
                        Uri toUpdate, HttpClient httpclient, HttpContext localContext, Map<URI, URI> uriRemap) {
        Collect.getInstance().getActivityLogger().logAction(this, urlString, instanceFilePath);
    ContentValues cv = new ContentValues();
    URI u = null;
    try {
        URL url = new URL(URLDecoder.decode(urlString, "utf-8"));
        u = url.toURI();
    } catch (MalformedURLException e) {
        e.printStackTrace();
        mResults.put(id,
            fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
        Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
        return true;
    } catch (URISyntaxException e) {
        e.printStackTrace();
        mResults.put(id,
            fail + "invalid uri: " + urlString + " :: details: " + e.getMessage());
        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
        Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
        return true;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        mResults.put(id,
            fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
        Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
        return true;
    }
    boolean openRosaServer = false;
    if (uriRemap.containsKey(u)) {
        // we already issued a head request and got a response,
        // so we know the proper URL to send the submission to
        // and the proper scheme. We also know that it was an
        // OpenRosa compliant server.
        openRosaServer = true;
        u = uriRemap.get(u);
    } else {
        // we need to issue a head request
        HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u);
        // prepare response
        HttpResponse response = null;
        try {
            response = httpclient.execute(httpHead, localContext);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 401) {
                WebUtils.discardEntityBytes(response);
                // we need authentication, so stop and return what we've
                // done so far.
                mAuthRequestingServer = u;
                return false;
            } else if (statusCode == 204) {
                Header[] locations = response.getHeaders("Location");
                WebUtils.discardEntityBytes(response);
                if (locations != null && locations.length == 1) {
                    try {
                        URL url =
                            new URL(URLDecoder.decode(locations[0].getValue(), "utf-8"));
                        URI uNew = url.toURI();
                        if (u.getHost().equalsIgnoreCase(uNew.getHost())) {
                            openRosaServer = true;
                            // trust the server to tell us a new location
                            // ... and possibly to use https instead.
                            uriRemap.put(u, uNew);
                            u = uNew;
                        } else {
                            // Don't follow a redirection attempt to a different host.
                            // We can't tell if this is a spoof or not.
                            mResults.put(
                                id,
                                fail
                                        + "Unexpected redirection attempt to a different host: "
                                        + uNew.toString());
                            cv.put(InstanceColumns.STATUS,
                                InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                            Collect.getInstance().getContentResolver()
                                    .update(toUpdate, cv, null, null);
                            return true;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        mResults.put(id, fail + urlString + " " + e.getMessage());
                        cv.put(InstanceColumns.STATUS,
                            InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                        Collect.getInstance().getContentResolver()
                                .update(toUpdate, cv, null, null);
                        return true;
                    }
                }
            } else {
                // may be a server that does not handle
                WebUtils.discardEntityBytes(response);
                Log.w(t, "Status code on Head request: " + statusCode);
                if (statusCode >= 200 && statusCode <= 299) {
                    mResults.put(
                        id,
                        fail
                                + "Invalid status code on Head request.  If you have a web proxy, you may need to login to your network. ");
                    cv.put(InstanceColumns.STATUS,
                        InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    Collect.getInstance().getContentResolver()
                            .update(toUpdate, cv, null, null);
                    return true;
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            Log.e(t, e.getMessage());
            mResults.put(id, fail + "Client Protocol Exception");
            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
            Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
            return true;
        } catch (ConnectTimeoutException e) {
            e.printStackTrace();
            Log.e(t, e.getMessage());
            mResults.put(id, fail + "Connection Timeout");
            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
            Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
            return true;
        } catch (UnknownHostException e) {
            e.printStackTrace();
            mResults.put(id, fail + e.getMessage() + " :: Network Connection Failed");
            Log.e(t, e.getMessage());
            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
            Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
            return true;
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
            Log.e(t, e.getMessage());
            mResults.put(id, fail + "Connection Timeout");
            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
            Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            mResults.put(id, fail + "Generic Exception");
            Log.e(t, e.getMessage());
            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
            Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
            return true;
        }
    }
    // At this point, we may have updated the uri to use https.
    // This occurs only if the Location header keeps the host name
    // the same. If it specifies a different host name, we error
    // out.
    //
    // And we may have set authentication cookies in our
    // cookiestore (referenced by localContext) that will enable
    // authenticated publication to the server.
    //
    // get instance file
    File instanceFile = new File(instanceFilePath);
    // Under normal operations, we upload the instanceFile to 
    // the server.  However, during the save, there is a failure
    // window that may mark the submission as complete but leave
    // the file-to-be-uploaded with the name "submission.xml" and
    // the plaintext submission files on disk.  In this case,
    // upload the submission.xml and all the files in the directory.
    // This means the plaintext files and the encrypted files 
    // will be sent to the server and the server will have to 
    // figure out what to do with them.
    File submissionFile = new File(instanceFile.getParentFile(), "submission.xml");
    if ( submissionFile.exists() ) {
        Log.w(t, "submission.xml will be uploaded instead of " + instanceFile.getAbsolutePath());
    } else {
        submissionFile = instanceFile;
    }
    if (!instanceFile.exists() && !submissionFile.exists()) {
        mResults.put(id, fail + "instance XML file does not exist!");
        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
        Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
        return true;
    }
    // find all files in parent directory
    File[] allFiles = instanceFile.getParentFile().listFiles();
    // add media files
    List<File> files = new ArrayList<File>();
    for (File f : allFiles) {
        String fileName = f.getName();
        int dotIndex = fileName.lastIndexOf(".");
        String extension = "";
        if (dotIndex != -1) {
            extension = fileName.substring(dotIndex + 1);
        }
        if (fileName.startsWith(".")) {
            // ignore invisible files
            continue;
        }
        if (fileName.equals(instanceFile.getName())) {
            continue; // the xml file has already been added
        } else if (fileName.equals(submissionFile.getName())) {
            continue; // the xml file has already been added
        } else if (openRosaServer) {
            files.add(f);
        } else if (extension.equals("jpg")) { // legacy 0.9x
            files.add(f);
        } else if (extension.equals("3gpp")) { // legacy 0.9x
            files.add(f);
        } else if (extension.equals("3gp")) { // legacy 0.9x
            files.add(f);
        } else if (extension.equals("mp4")) { // legacy 0.9x
            files.add(f);
        } else {
            Log.w(t, "unrecognized file type " + f.getName());
        }
    }
    boolean first = true;
    int j = 0;
    int lastJ;
    while (j < files.size() || first) {
        lastJ = j;
        first = false;
        HttpPost httppost = WebUtils.createOpenRosaHttpPost(u, mAuth);
        MimeTypeMap m = MimeTypeMap.getSingleton();
        long byteCount = 0L;
        // mime post
        MultipartEntity entity = new MultipartEntity();
        // add the submission file first...
        FileBody fb = new FileBody(submissionFile, "text/xml");
        entity.addPart("xml_submission_file", fb);
        Log.i(t, "added xml_submission_file: " + submissionFile.getName());
        byteCount += submissionFile.length();
        for (; j < files.size(); j++) {
            File f = files.get(j);
            String fileName = f.getName();
            int idx = fileName.lastIndexOf(".");
            String extension = "";
            if (idx != -1) {
                extension = fileName.substring(idx + 1);
            }
            String contentType = m.getMimeTypeFromExtension(extension);
            // we will be processing every one of these, so
            // we only need to deal with the content type determination...
            if (extension.equals("xml")) {
                fb = new FileBody(f, "text/xml");
                entity.addPart(f.getName(), fb);
                byteCount += f.length();
                Log.i(t, "added xml file " + f.getName());
            } else if (extension.equals("jpg")) {
                fb = new FileBody(f, "image/jpeg");
                entity.addPart(f.getName(), fb);
                byteCount += f.length();
                Log.i(t, "added image file " + f.getName());
            } else if (extension.equals("3gpp")) {
                fb = new FileBody(f, "audio/3gpp");
                entity.addPart(f.getName(), fb);
                byteCount += f.length();
                Log.i(t, "added audio file " + f.getName());
            } else if (extension.equals("3gp")) {
                fb = new FileBody(f, "video/3gpp");
                entity.addPart(f.getName(), fb);
                byteCount += f.length();
                Log.i(t, "added video file " + f.getName());
            } else if (extension.equals("mp4")) {
                fb = new FileBody(f, "video/mp4");
                entity.addPart(f.getName(), fb);
                byteCount += f.length();
                Log.i(t, "added video file " + f.getName());
            } else if (extension.equals("csv")) {
                fb = new FileBody(f, "text/csv");
                entity.addPart(f.getName(), fb);
                byteCount += f.length();
                Log.i(t, "added csv file " + f.getName());
            } else if (f.getName().endsWith(".amr")) {
                fb = new FileBody(f, "audio/amr");
                entity.addPart(f.getName(), fb);
                Log.i(t, "added audio file " + f.getName());
            } else if (extension.equals("xls")) {
                fb = new FileBody(f, "application/vnd.ms-excel");
                entity.addPart(f.getName(), fb);
                byteCount += f.length();
                Log.i(t, "added xls file " + f.getName());
            } else if (contentType != null) {
                fb = new FileBody(f, contentType);
                entity.addPart(f.getName(), fb);
                byteCount += f.length();
                Log.i(t,
                    "added recognized filetype (" + contentType + ") " + f.getName());
            } else {
                contentType = "application/octet-stream";
                fb = new FileBody(f, contentType);
                entity.addPart(f.getName(), fb);
                byteCount += f.length();
                Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName());
            }
            // we've added at least one attachment to the request...
            if (j + 1 < files.size()) {
                if ((j-lastJ+1 > 100) || (byteCount + files.get(j + 1).length() > 10000000L)) {
                    // the next file would exceed the 10MB threshold...
                    Log.i(t, "Extremely long post is being split into multiple posts");
                    try {
                        StringBody sb = new StringBody("yes", Charset.forName("UTF-8"));
                        entity.addPart("*isIncomplete*", sb);
                    } catch (Exception e) {
                        e.printStackTrace(); // never happens...
                    }
                    ++j; // advance over the last attachment added...
                    break;
                }
            }
        }
        httppost.setEntity(entity);
        // prepare response and return uploaded
        HttpResponse response = null;
        try {
            response = httpclient.execute(httppost, localContext);
            int responseCode = response.getStatusLine().getStatusCode();
            WebUtils.discardEntityBytes(response);
            Log.i(t, "Response code:" + responseCode);
            // verify that the response was a 201 or 202.
            // If it wasn't, the submission has failed.
            if (responseCode != 201 && responseCode != 202) {
                if (responseCode == 200) {
                    mResults.put(id, fail + "Network login failure? Again?");
                } else {
                    mResults.put(id, fail + response.getStatusLine().getReasonPhrase()
                            + " (" + responseCode + ") at " + urlString);
                }
                cv.put(InstanceColumns.STATUS,
                    InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                Collect.getInstance().getContentResolver()
                        .update(toUpdate, cv, null, null);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            mResults.put(id, fail + "Generic Exception. " + e.getMessage());
            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
            Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
            return true;
        }
    }
    // if it got here, it must have worked
    mResults.put(id, Collect.getInstance().getString(R.string.success));
    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED);
    Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
    return true;
}
 

实例 13


@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
        long requestStart = SystemClock.elapsedRealtime();
        while (true) {
                HttpResponse httpResponse = null;
                HttpEntity responseContents = null;
                Map<String, String> responseHeaders = Collections.emptyMap();
                try {
                        // Gather headers.
                        Map<String, String> headers = new HashMap<String, String>();
                        addCacheHeaders(headers, request.getCacheEntry());
                        httpResponse = mHttpStack.performRequest(request, headers);
                        StatusLine statusLine = httpResponse.getStatusLine();
                        int statusCode = statusLine.getStatusCode();
                        responseHeaders = convertHeaders(httpResponse.getAllHeaders());
                        // Handle cache validation.
                        if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
                                Entry entry = request.getCacheEntry();
                                if (entry == null) {
                                        return new QMusicNetworkResponse(HttpStatus.SC_NOT_MODIFIED, null, responseHeaders, true, SystemClock.elapsedRealtime() - requestStart);
                                }
                                // A HTTP 304 response does not have all header fields. We
                                // have to use the header fields from the cache entry plus
                                // the new ones from the response.
                                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
                                entry.responseHeaders.putAll(responseHeaders);
                                return new QMusicNetworkResponse(HttpStatus.SC_NOT_MODIFIED, null, entry.responseHeaders, true, SystemClock.elapsedRealtime()
                                                - requestStart);
                        }
                        // Some responses such as 204s do not have content. We must
                        // check.
                        if (httpResponse.getEntity() != null) {
                                // TODO:
                                responseContents = httpResponse.getEntity();
                        } else {
                                // Add 0 byte response as a way of honestly representing a
                                // no-content request.
                                // responseContents = new byte[0];
                        }
                        // if the request is slow, log it.
                        long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
                        logSlowRequests(requestLifetime, request, responseContents, statusLine);
                        if (statusCode < 200 || statusCode > 299) {
                                throw new IOException();
                        }
                        return new QMusicNetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart);
                } catch (SocketTimeoutException e) {
                        attemptRetryOnException("socket", request, new TimeoutError());
                } catch (ConnectTimeoutException e) {
                        attemptRetryOnException("connection", request, new TimeoutError());
                } catch (MalformedURLException e) {
                        throw new RuntimeException("Bad URL " + request.getUrl(), e);
                } catch (IOException e) {
                        int statusCode = 0;
                        NetworkResponse networkResponse = null;
                        if (httpResponse != null) {
                                statusCode = httpResponse.getStatusLine().getStatusCode();
                        } else {
                                throw new NoConnectionError(e);
                        }
                        VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
                        if (responseContents != null) {
                                networkResponse = new QMusicNetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime()
                                                - requestStart);
                                if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                                        attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                                } else {
                                        // TODO: Only throw ServerError for 5xx status codes.
                                        throw new ServerError(networkResponse);
                                }
                        } else {
                                throw new NetworkError(networkResponse);
                        }
                }
        }
}
 

实例 14


private int copy(InputStream input, RandomAccessFile output, boolean isRangeDownload) 
                throws IOException, NetworkErrorException {
    if (input == null || output == null) {
        return -1;
    }
    byte[] buffer = new byte[BUFFER_SIZE];
    BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
    if (DEBUG) {
        Log.v(TAG, "length " + output.length());
    }
    int count = 0, n = 0;
    long errorBlockTimePreviousTime = -1, expireTime = 0;
    try {
        if (isRangeDownload) {
            output.seek(output.length());
        }
        while (!mInterrupt) {
            n = in.read(buffer, 0, BUFFER_SIZE);
            if (n == -1) {
                break;
            }
            output.write(buffer, 0, n);
            count += n;
            /*
             * check network
             */
            if (!NetworkUtils.isNetworkAvailable(mContext)) {
                throw new NetworkErrorException("Network blocked.");
            }
            if (mNetworkSpeed == 0) {
                if (errorBlockTimePreviousTime > 0) {
                    expireTime = System.currentTimeMillis() - errorBlockTimePreviousTime;
                    if (expireTime > TIME_OUT) {
                        throw new ConnectTimeoutException("connection time out.");
                    }
                } else {
                    errorBlockTimePreviousTime = System.currentTimeMillis();
                }
            } else {
                expireTime = 0;
                errorBlockTimePreviousTime = -1;
            }
        }
    } finally {
        mConnection.disconnect();
        mConnection = null;
        output.close();
        in.close();
        input.close();
    }
    return count;
}
 

实例 15


@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = Collections.emptyMap();
        try {
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // Handle cache validation.
            if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
                Entry entry = request.getCacheEntry();
                if (entry == null) {
                    return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, null,
                            responseHeaders, true,
                            SystemClock.elapsedRealtime() - requestStart);
                }
                // A HTTP 304 response does not have all header fields. We
                // have to use the header fields from the cache entry plus
                // the new ones from the response.
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
                entry.responseHeaders.putAll(responseHeaders);
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, entry.data,
                        entry.responseHeaders, true,
                        SystemClock.elapsedRealtime() - requestStart);
            }
            // Handle moved resources
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                String newUrl = responseHeaders.get("Location");
                request.setRedirectUrl(newUrl);
            }
            // Some responses such as 204s do not have content.  We must check.
            if (httpResponse.getEntity() != null) {
              responseContents = entityToBytes(httpResponse.getEntity());
            } else {
              // Add 0 byte response as a way of honestly representing a
              // no-content request.
              responseContents = new byte[0];
            }
            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, statusLine);
            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false,
                    SystemClock.elapsedRealtime() - requestStart);
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || 
                        statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                VolleyLog.e("Request at %s has been redirected to %s", request.getOriginUrl(), request.getUrl());
            } else {
                VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            }
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents,
                        responseHeaders, false, SystemClock.elapsedRealtime() - requestStart);
                if (statusCode == HttpStatus.SC_UNAUTHORIZED ||
                        statusCode == HttpStatus.SC_FORBIDDEN) {
                    attemptRetryOnException("auth",
                            request, new AuthFailureError(networkResponse));
                } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || 
                                        statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                    attemptRetryOnException("redirect",
                            request, new RedirectError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(e);
            }
        }
    }
}
 
讨论
淘淘あ西西 profile image