Search in sources :

Example 46 with SocketTimeoutException

use of java.net.SocketTimeoutException in project openhab1-addons by openhab.

the class SsdpDiscovery method retrieveResponse.

static Map<String, Map<String, String>> retrieveResponse() throws Exception {
    String response = null;
    Map<String, Map<String, String>> result = new HashMap<String, Map<String, String>>();
    MulticastSocket recSocket = setUpSocket();
    int i = 0;
    logger.debug("Retrieving response");
    while (i < 10) {
        byte[] buf = new byte[2048];
        DatagramPacket input = new DatagramPacket(buf, buf.length);
        try {
            recSocket.receive(input);
            response = new String(input.getData());
            Map<String, String> parsedResponse = parseResponse(response);
            result.put(parsedResponse.get("IP"), parsedResponse);
        } catch (SocketTimeoutException e) {
            if (i >= 10) {
                break;
            }
            i++;
        }
    }
    logger.debug("Response retrieved: {}", result);
    return result;
}
Also used : MulticastSocket(java.net.MulticastSocket) SocketTimeoutException(java.net.SocketTimeoutException) HashMap(java.util.HashMap) DatagramPacket(java.net.DatagramPacket) HashMap(java.util.HashMap) Map(java.util.Map)

Example 47 with SocketTimeoutException

use of java.net.SocketTimeoutException in project OpenAM by OpenRock.

the class Notifier method postRequest.

private boolean postRequest(String strURL, String data) throws IOException {
    OutputStreamWriter wr = null;
    try {
        URL url = new URL(strURL);
        HttpURLConnection conn = HttpURLConnectionManager.getConnection(url);
        conn.setConnectTimeout(CONN_TIMEOUT);
        conn.setDoOutput(true);
        wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        int status = conn.getResponseCode();
        return (status == HttpURLConnection.HTTP_OK);
    } catch (SocketTimeoutException e) {
        PolicyConstants.DEBUG.error("Notifier.post", e);
        return false;
    } finally {
        if (wr != null) {
            wr.close();
        }
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) SocketTimeoutException(java.net.SocketTimeoutException) OutputStreamWriter(java.io.OutputStreamWriter) URL(java.net.URL)

Example 48 with SocketTimeoutException

use of java.net.SocketTimeoutException in project otertool by wuntee.

the class JarSigner method signJar.

void signJar(String jarName, String alias, String[] args) throws Exception {
    boolean aliasUsed = false;
    X509Certificate tsaCert = null;
    if (sigfile == null) {
        sigfile = alias;
        aliasUsed = true;
    }
    if (sigfile.length() > 8) {
        sigfile = sigfile.substring(0, 8).toUpperCase();
    } else {
        sigfile = sigfile.toUpperCase();
    }
    StringBuilder tmpSigFile = new StringBuilder(sigfile.length());
    for (int j = 0; j < sigfile.length(); j++) {
        char c = sigfile.charAt(j);
        if (!((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '-') || (c == '_'))) {
            if (aliasUsed) {
                // convert illegal characters from the alias to be _'s
                c = '_';
            } else {
                throw new RuntimeException(rb.getString("signature filename must consist of the following characters: A-Z, 0-9, _ or -"));
            }
        }
        tmpSigFile.append(c);
    }
    sigfile = tmpSigFile.toString();
    String tmpJarName;
    if (signedjar == null)
        tmpJarName = jarName + ".sig";
    else
        tmpJarName = signedjar;
    File jarFile = new File(jarName);
    File signedJarFile = new File(tmpJarName);
    // Open the jar (zip) file
    try {
        zipFile = new ZipFile(jarName);
    } catch (IOException ioe) {
        error(rb.getString("unable to open jar file: ") + jarName, ioe);
    }
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(signedJarFile);
    } catch (IOException ioe) {
        error(rb.getString("unable to create: ") + tmpJarName, ioe);
    }
    PrintStream ps = new PrintStream(fos);
    ZipOutputStream zos = new ZipOutputStream(ps);
    /* First guess at what they might be - we don't xclude RSA ones. */
    String sfFilename = (META_INF + sigfile + ".SF").toUpperCase();
    String bkFilename = (META_INF + sigfile + ".DSA").toUpperCase();
    Manifest manifest = new Manifest();
    Map<String, Attributes> mfEntries = manifest.getEntries();
    // The Attributes of manifest before updating
    Attributes oldAttr = null;
    boolean mfModified = false;
    boolean mfCreated = false;
    byte[] mfRawBytes = null;
    try {
        MessageDigest[] digests = { MessageDigest.getInstance(digestalg) };
        // Check if manifest exists
        ZipEntry mfFile;
        if ((mfFile = getManifestFile(zipFile)) != null) {
            // Manifest exists. Read its raw bytes.
            mfRawBytes = getBytes(zipFile, mfFile);
            manifest.read(new ByteArrayInputStream(mfRawBytes));
            oldAttr = (Attributes) (manifest.getMainAttributes().clone());
        } else {
            // Create new manifest
            Attributes mattr = manifest.getMainAttributes();
            mattr.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
            String javaVendor = System.getProperty("java.vendor");
            String jdkVersion = System.getProperty("java.version");
            mattr.putValue("Created-By", jdkVersion + " (" + javaVendor + ")");
            mfFile = new ZipEntry(JarFile.MANIFEST_NAME);
            mfCreated = true;
        }
        /*
             * For each entry in jar
             * (except for signature-related META-INF entries),
             * do the following:
             *
             * - if entry is not contained in manifest, add it to manifest;
             * - if entry is contained in manifest, calculate its hash and
             *   compare it with the one in the manifest; if they are
             *   different, replace the hash in the manifest with the newly
             *   generated one. (This may invalidate existing signatures!)
             */
        BASE64Encoder encoder = new JarBASE64Encoder();
        Vector<ZipEntry> mfFiles = new Vector<ZipEntry>();
        for (Enumeration<? extends ZipEntry> enum_ = zipFile.entries(); enum_.hasMoreElements(); ) {
            ZipEntry ze = enum_.nextElement();
            if (ze.getName().startsWith(META_INF)) {
                // Store META-INF files in vector, so they can be written
                // out first
                mfFiles.addElement(ze);
                if (signatureRelated(ze.getName())) {
                    // ignore signature-related and manifest files
                    continue;
                }
            }
            if (manifest.getAttributes(ze.getName()) != null) {
                // possibly update its digest attributes
                if (updateDigests(ze, zipFile, digests, encoder, manifest) == true) {
                    mfModified = true;
                }
            } else if (!ze.isDirectory()) {
                // Add entry to manifest
                Attributes attrs = getDigestAttributes(ze, zipFile, digests, encoder);
                mfEntries.put(ze.getName(), attrs);
                mfModified = true;
            }
        }
        // Recalculate the manifest raw bytes if necessary
        if (mfModified) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            manifest.write(baos);
            byte[] newBytes = baos.toByteArray();
            if (mfRawBytes != null && oldAttr.equals(manifest.getMainAttributes())) {
                /*
                     * Note:
                     *
                     * The Attributes object is based on HashMap and can handle
                     * continuation columns. Therefore, even if the contents are 
                     * not changed (in a Map view), the bytes that it write() 
                     * may be different from the original bytes that it read()
                     * from. Since the signature on the main attributes is based 
                     * on raw bytes, we must retain the exact bytes.
                     */
                int newPos = findHeaderEnd(newBytes);
                int oldPos = findHeaderEnd(mfRawBytes);
                if (newPos == oldPos) {
                    System.arraycopy(mfRawBytes, 0, newBytes, 0, oldPos);
                } else {
                    // cat oldHead newTail > newBytes
                    byte[] lastBytes = new byte[oldPos + newBytes.length - newPos];
                    System.arraycopy(mfRawBytes, 0, lastBytes, 0, oldPos);
                    System.arraycopy(newBytes, newPos, lastBytes, oldPos, newBytes.length - newPos);
                    newBytes = lastBytes;
                }
            }
            mfRawBytes = newBytes;
        }
        // Write out the manifest
        if (mfModified) {
            // manifest file has new length
            mfFile = new ZipEntry(JarFile.MANIFEST_NAME);
        }
        zos.putNextEntry(mfFile);
        zos.write(mfRawBytes);
        // Calculate SignatureFile (".SF") and SignatureBlockFile
        ManifestDigester manDig = new ManifestDigester(mfRawBytes);
        SignatureFile sf = new SignatureFile(digests, manifest, manDig, sigfile, signManifest);
        if (tsaAlias != null) {
            tsaCert = getTsaCert(tsaAlias);
        }
        SignatureFile.Block block = null;
        try {
            block = sf.generateBlock(privateKey, sigalg, certChain, externalSF, tsaUrl, tsaCert, signingMechanism, args, zipFile);
        } catch (SocketTimeoutException e) {
            // Provide a helpful message when TSA is beyond a firewall
            error(rb.getString("unable to sign jar: ") + rb.getString("no response from the Timestamping Authority. ") + rb.getString("When connecting from behind a firewall then an HTTP proxy may need to be specified. ") + rb.getString("Supply the following options to jarsigner: ") + "\n  -J-Dhttp.proxyHost=<hostname> " + "\n  -J-Dhttp.proxyPort=<portnumber> ", e);
        }
        sfFilename = sf.getMetaName();
        bkFilename = block.getMetaName();
        ZipEntry sfFile = new ZipEntry(sfFilename);
        ZipEntry bkFile = new ZipEntry(bkFilename);
        long time = System.currentTimeMillis();
        sfFile.setTime(time);
        bkFile.setTime(time);
        // signature file
        zos.putNextEntry(sfFile);
        sf.write(zos);
        // signature block file
        zos.putNextEntry(bkFile);
        block.write(zos);
        // vector
        for (int i = 0; i < mfFiles.size(); i++) {
            ZipEntry ze = mfFiles.elementAt(i);
            if (!ze.getName().equalsIgnoreCase(JarFile.MANIFEST_NAME) && !ze.getName().equalsIgnoreCase(sfFilename) && !ze.getName().equalsIgnoreCase(bkFilename)) {
                writeEntry(zipFile, zos, ze);
            }
        }
        // Write out all other files
        for (Enumeration<? extends ZipEntry> enum_ = zipFile.entries(); enum_.hasMoreElements(); ) {
            ZipEntry ze = enum_.nextElement();
            if (!ze.getName().startsWith(META_INF)) {
                writeEntry(zipFile, zos, ze);
            }
        }
    } catch (IOException ioe) {
        error(rb.getString("unable to sign jar: ") + ioe, ioe);
    } finally {
        // close the resouces
        if (zipFile != null) {
            zipFile.close();
            zipFile = null;
        }
        if (zos != null) {
            zos.close();
        }
    }
    // try {
    if (signedjar == null) {
        // one, then delete the original.
        if (!signedJarFile.renameTo(jarFile)) {
            File origJar = new File(jarName + ".orig");
            if (jarFile.renameTo(origJar)) {
                if (signedJarFile.renameTo(jarFile)) {
                    origJar.delete();
                } else {
                    MessageFormat form = new MessageFormat(rb.getString("attempt to rename signedJarFile to jarFile failed"));
                    Object[] source = { signedJarFile, jarFile };
                    error(form.format(source));
                }
            } else {
                MessageFormat form = new MessageFormat(rb.getString("attempt to rename jarFile to origJar failed"));
                Object[] source = { jarFile, origJar };
                error(form.format(source));
            }
        }
    }
    if (hasExpiredCert || hasExpiringCert || notYetValidCert || badKeyUsage || badExtendedKeyUsage || badNetscapeCertType) {
        logger.warn(rb.getString("Warning: "));
        if (badKeyUsage) {
            logger.warn(rb.getString("The signer certificate's KeyUsage extension doesn't allow code signing."));
        }
        if (badExtendedKeyUsage) {
            logger.warn(rb.getString("The signer certificate's ExtendedKeyUsage extension doesn't allow code signing."));
        }
        if (badNetscapeCertType) {
            logger.warn(rb.getString("The signer certificate's NetscapeCertType extension doesn't allow code signing."));
        }
        if (hasExpiredCert) {
            logger.warn(rb.getString("The signer certificate has expired."));
        } else if (hasExpiringCert) {
            logger.warn(rb.getString("The signer certificate will expire within six months."));
        } else if (notYetValidCert) {
            logger.warn(rb.getString("The signer certificate is not yet valid."));
        }
    }
// no IOException thrown in the above try clause, so disable
// the catch clause.
// } catch(IOException ioe) {
//     error(rb.getString("unable to sign jar: ")+ioe, ioe);
// }
}
Also used : ZipEntry(java.util.zip.ZipEntry) Attributes(java.util.jar.Attributes) MessageDigest(java.security.MessageDigest) Vector(java.util.Vector) PrintStream(java.io.PrintStream) MessageFormat(java.text.MessageFormat) BASE64Encoder(sun.misc.BASE64Encoder) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Manifest(java.util.jar.Manifest) X509Certificate(java.security.cert.X509Certificate) SocketTimeoutException(java.net.SocketTimeoutException) ZipFile(java.util.zip.ZipFile) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipOutputStream(java.util.zip.ZipOutputStream) ManifestDigester(sun.security.util.ManifestDigester) FileOutputStream(java.io.FileOutputStream) JarFile(java.util.jar.JarFile) ZipFile(java.util.zip.ZipFile) File(java.io.File)

Example 49 with SocketTimeoutException

use of java.net.SocketTimeoutException in project NoHttp by yanzhenjie.

the class Downloader method download.

public void download(int what, DownloadRequest downloadRequest, DownloadListener downloadListener) {
    validateParam(downloadRequest, downloadListener);
    Connection connection = null;
    RandomAccessFile randomAccessFile = null;
    String savePathDir = downloadRequest.getFileDir();
    String fileName = downloadRequest.getFileName();
    try {
        if (TextUtils.isEmpty(savePathDir))
            savePathDir = NoHttp.getContext().getFilesDir().getAbsolutePath();
        validateDevice(savePathDir);
        if (// auto named.
        TextUtils.isEmpty(fileName))
            fileName = Long.toString(System.currentTimeMillis());
        File tempFile = new File(savePathDir, fileName + ".nohttp");
        // 断点开始处。
        long rangeSize = handleRange(tempFile, downloadRequest);
        // 连接服务器。
        connection = mHttpConnection.getConnection(downloadRequest);
        Exception exception = connection.exception();
        if (exception != null)
            throw exception;
        Logger.i("----------Response Start----------");
        Headers responseHeaders = connection.responseHeaders();
        int responseCode = responseHeaders.getResponseCode();
        // getList filename from server.
        if (downloadRequest.autoNameByHead()) {
            String contentDisposition = responseHeaders.getContentDisposition();
            if (!TextUtils.isEmpty(contentDisposition)) {
                fileName = HeaderUtil.parseHeadValue(contentDisposition, "filename", null);
                if (!TextUtils.isEmpty(fileName)) {
                    try {
                        fileName = URLDecoder.decode(fileName, downloadRequest.getParamsEncoding());
                    } catch (UnsupportedEncodingException e) {
                    // Do nothing.
                    }
                    if (fileName.startsWith("\"") && fileName.endsWith("\"")) {
                        fileName = fileName.substring(1, fileName.length() - 1);
                    }
                }
            }
            // From url.
            if (TextUtils.isEmpty(fileName)) {
                String tempUrl = downloadRequest.url();
                String[] slash = tempUrl.split("/");
                fileName = slash[slash.length - 1];
                int paramIndex = fileName.indexOf("?");
                if (paramIndex > 0) {
                    fileName = fileName.substring(0, paramIndex);
                }
            }
        }
        InputStream serverStream = connection.serverStream();
        if (responseCode >= 400) {
            ServerError error = new ServerError("Download failed, the server response code is " + responseCode + ": " + downloadRequest.url());
            error.setErrorBody(IOUtils.toString(serverStream));
            throw error;
        } else {
            long contentLength;
            // 文件总大小
            if (responseCode == 206) {
                // Content-Range: bytes [文件块的开始字节]-[文件的总大小 - 1]/[文件的总大小]。
                // Sample:Accept-Range:bytes 1024-2047/2048。
                String range = responseHeaders.getContentRange();
                try {
                    // 截取'/'之后的总大小。
                    contentLength = Long.parseLong(range.substring(range.indexOf('/') + 1));
                } catch (Throwable e) {
                    throw new ServerError("ResponseCode is 206, but content-Range error in Server HTTP header " + "information: " + range + ".");
                }
            } else if (responseCode == 304) {
                int httpContentLength = responseHeaders.getContentLength();
                downloadListener.onStart(what, true, httpContentLength, responseHeaders, httpContentLength);
                downloadListener.onProgress(what, 100, httpContentLength, 0);
                Logger.d("-------Download finish-------");
                downloadListener.onFinish(what, savePathDir + File.separator + fileName);
                return;
            } else {
                // such as: 200.
                // 服务器不支持Range。
                rangeSize = 0L;
                // 直接下载。
                contentLength = responseHeaders.getContentLength();
            }
            // 验证文件已经存在。
            File lastFile = new File(savePathDir, fileName);
            if (lastFile.exists()) {
                if (downloadRequest.isDeleteOld())
                    IOUtils.delFileOrFolder(lastFile);
                else {
                    downloadListener.onStart(what, true, lastFile.length(), responseHeaders, lastFile.length());
                    downloadListener.onProgress(what, 100, lastFile.length(), 0);
                    Logger.d("-------Download finish-------");
                    downloadListener.onFinish(what, lastFile.getAbsolutePath());
                    return;
                }
            }
            if (IOUtils.getDirSize(savePathDir) < contentLength)
                throw new StorageSpaceNotEnoughError("The folder is not enough space to save the downloaded file:" + " " + savePathDir + ".");
            // 需要重新下载,生成临时文件。
            if (responseCode != 206 && !IOUtils.createNewFile(tempFile))
                throw new StorageReadWriteError("SD isn't available, please check SD card and permission: " + "WRITE_EXTERNAL_STORAGE, and you must pay attention to Android6.0 RunTime " + "Permissions: https://github.com/yanzhenjie/AndPermission.");
            if (downloadRequest.isCanceled()) {
                Log.w("NoHttpDownloader", "Download request is canceled.");
                downloadListener.onCancel(what);
                return;
            }
            // 通知开始下载了。
            Logger.d("-------Download start-------");
            downloadListener.onStart(what, rangeSize > 0, rangeSize, responseHeaders, contentLength);
            randomAccessFile = new RandomAccessFile(tempFile, "rws");
            randomAccessFile.seek(rangeSize);
            byte[] buffer = new byte[8096];
            int len;
            // 旧的进度记录,防止重复通知。
            int oldProgress = 0;
            // 追加目前已经下载的进度。
            long count = rangeSize;
            long startTime = System.currentTimeMillis();
            long speedCount = 0;
            long oldSpeed = 0;
            while (((len = serverStream.read(buffer)) != -1)) {
                if (downloadRequest.isCanceled()) {
                    Log.i("NoHttpDownloader", "Download request is canceled.");
                    downloadListener.onCancel(what);
                    break;
                } else {
                    randomAccessFile.write(buffer, 0, len);
                    count += len;
                    speedCount += len;
                    long time = System.currentTimeMillis() - startTime;
                    long speed = speedCount * 1000 / time;
                    boolean speedChanged = oldSpeed != speed && time >= 300;
                    Logger.i("speedCount: " + speedCount + "; time: " + time + "; speed: " + speed + "; changed: " + "" + speedChanged);
                    if (contentLength != 0) {
                        int progress = (int) (count * 100 / contentLength);
                        if (progress != oldProgress && speedChanged) {
                            downloadListener.onProgress(what, progress, count, speed);
                            speedCount = 0;
                            oldSpeed = speed;
                            startTime = System.currentTimeMillis();
                        } else if (speedChanged) {
                            downloadListener.onProgress(what, oldProgress, count, speed);
                            speedCount = 0;
                            oldSpeed = speed;
                            startTime = System.currentTimeMillis();
                        } else if (progress != oldProgress) {
                            downloadListener.onProgress(what, progress, count, oldSpeed);
                        }
                        oldProgress = progress;
                    } else if (speedChanged) {
                        downloadListener.onProgress(what, 0, count, speed);
                        speedCount = 0;
                        oldSpeed = speed;
                        startTime = System.currentTimeMillis();
                    } else {
                        downloadListener.onProgress(what, 0, count, oldSpeed);
                    }
                }
            }
            if (!downloadRequest.isCanceled()) {
                //noinspection ResultOfMethodCallIgnored
                tempFile.renameTo(lastFile);
                Logger.d("-------Download finish-------");
                downloadListener.onFinish(what, lastFile.getAbsolutePath());
            }
        }
    } catch (MalformedURLException e) {
        Logger.e(e);
        downloadListener.onDownloadError(what, new URLError(e.getMessage()));
    } catch (UnknownHostException e) {
        Logger.e(e);
        downloadListener.onDownloadError(what, new UnKnownHostError(e.getMessage()));
    } catch (SocketTimeoutException e) {
        Logger.e(e);
        downloadListener.onDownloadError(what, new TimeoutError(e.getMessage()));
    } catch (IOException e) {
        Exception newException = e;
        if (!IOUtils.canWrite(savePathDir))
            newException = new StorageReadWriteError("This folder cannot be written to the file: " + savePathDir + ".");
        else if (IOUtils.getDirSize(savePathDir) < 1024)
            newException = new StorageSpaceNotEnoughError("The folder is not enough space to save the downloaded " + "file: " + savePathDir + ".");
        Logger.e(newException);
        downloadListener.onDownloadError(what, newException);
    } catch (Exception e) {
        // NetworkError | ServerError | StorageCantWriteError | StorageSpaceNotEnoughError
        if (!NetUtil.isNetworkAvailable())
            e = new NetworkError("The network is not available.");
        Logger.e(e);
        downloadListener.onDownloadError(what, e);
    } finally {
        Logger.i("----------Response End----------");
        IOUtils.closeQuietly(randomAccessFile);
        IOUtils.closeQuietly(connection);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) Headers(com.yanzhenjie.nohttp.Headers) URLError(com.yanzhenjie.nohttp.error.URLError) UnknownHostException(java.net.UnknownHostException) InputStream(java.io.InputStream) ServerError(com.yanzhenjie.nohttp.error.ServerError) StorageReadWriteError(com.yanzhenjie.nohttp.error.StorageReadWriteError) Connection(com.yanzhenjie.nohttp.Connection) HttpConnection(com.yanzhenjie.nohttp.HttpConnection) UnsupportedEncodingException(java.io.UnsupportedEncodingException) StorageSpaceNotEnoughError(com.yanzhenjie.nohttp.error.StorageSpaceNotEnoughError) NetworkError(com.yanzhenjie.nohttp.error.NetworkError) TimeoutError(com.yanzhenjie.nohttp.error.TimeoutError) IOException(java.io.IOException) SocketTimeoutException(java.net.SocketTimeoutException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SocketTimeoutException(java.net.SocketTimeoutException) RandomAccessFile(java.io.RandomAccessFile) UnKnownHostError(com.yanzhenjie.nohttp.error.UnKnownHostError) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 50 with SocketTimeoutException

use of java.net.SocketTimeoutException in project NoHttp by yanzhenjie.

the class HttpConnection method getConnection.

/**
     * Send the request, send only head, parameters, such as file information.
     *
     * @param request {@link IBasicRequest}.
     * @return {@link Connection}.
     */
public Connection getConnection(IBasicRequest request) {
    Logger.d("--------------Request start--------------");
    Headers responseHeaders = new HttpHeaders();
    InputStream inputStream = null;
    Exception exception = null;
    Network network = null;
    String url = request.url();
    try {
        if (!NetUtil.isNetworkAvailable())
            throw new NetworkError("The network is not available, please check the network. The requested url is:" + " " + url);
        // MalformedURLException, IOException, ProtocolException, UnknownHostException, SocketTimeoutException
        network = createConnectionAndWriteData(request);
        Logger.d("-------Response start-------");
        int responseCode = network.getResponseCode();
        responseHeaders = parseResponseHeaders(new URI(request.url()), responseCode, network.getResponseHeaders());
        // handle body
        if (responseCode == 301 || responseCode == 302 || responseCode == 303 || responseCode == 307) {
            Connection redirectConnection = handleRedirect(request, responseHeaders);
            responseHeaders = redirectConnection.responseHeaders();
            inputStream = redirectConnection.serverStream();
            exception = redirectConnection.exception();
        } else if (hasResponseBody(request.getRequestMethod(), responseCode)) {
            inputStream = network.getServerStream(responseCode, responseHeaders);
        }
        Logger.d("-------Response end-------");
    } catch (MalformedURLException e) {
        exception = new URLError("The url is malformed: " + url + ".");
    } catch (UnknownHostException e) {
        exception = new UnKnownHostError("Hostname can not be resolved: " + url + ".");
    } catch (SocketTimeoutException e) {
        exception = new TimeoutError("Request time out: " + url + ".");
    } catch (Exception e) {
        exception = e;
    } finally {
        if (exception != null)
            Logger.e(exception);
    }
    Logger.d("--------------Request finish--------------");
    return new Connection(network, responseHeaders, inputStream, exception);
}
Also used : MalformedURLException(java.net.MalformedURLException) UnknownHostException(java.net.UnknownHostException) InputStream(java.io.InputStream) HttpURLConnection(java.net.HttpURLConnection) NetworkError(com.yanzhenjie.nohttp.error.NetworkError) TimeoutError(com.yanzhenjie.nohttp.error.TimeoutError) URLError(com.yanzhenjie.nohttp.error.URLError) URI(java.net.URI) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) SocketTimeoutException(java.net.SocketTimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) UnKnownHostError(com.yanzhenjie.nohttp.error.UnKnownHostError)

Aggregations

SocketTimeoutException (java.net.SocketTimeoutException)721 IOException (java.io.IOException)420 Test (org.junit.Test)139 Socket (java.net.Socket)103 SocketException (java.net.SocketException)99 ServerSocket (java.net.ServerSocket)79 InputStream (java.io.InputStream)77 ConnectException (java.net.ConnectException)70 UnknownHostException (java.net.UnknownHostException)64 InetSocketAddress (java.net.InetSocketAddress)60 URL (java.net.URL)51 EOFException (java.io.EOFException)48 HttpURLConnection (java.net.HttpURLConnection)47 ConnectTimeoutException (org.apache.http.conn.ConnectTimeoutException)42 InterruptedIOException (java.io.InterruptedIOException)40 ArrayList (java.util.ArrayList)40 MalformedURLException (java.net.MalformedURLException)38 InputStreamReader (java.io.InputStreamReader)37 HashMap (java.util.HashMap)36 OutputStream (java.io.OutputStream)35