Search in sources :

Example 91 with Proxy

use of java.net.Proxy in project weiciyuan by qii.

the class JavaHttpUtility method doGetSaveFile.

public boolean doGetSaveFile(String urlStr, String path, FileDownloaderHttpHelper.DownloadListener downloadListener) {
    File file = FileManager.createNewFileInSDCard(path);
    if (file == null) {
        return false;
    }
    boolean result = false;
    BufferedOutputStream out = null;
    InputStream in = null;
    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(urlStr);
        AppLogger.d("download request=" + urlStr);
        Proxy proxy = getProxy();
        if (proxy != null) {
            urlConnection = (HttpURLConnection) url.openConnection(proxy);
        } else {
            urlConnection = (HttpURLConnection) url.openConnection();
        }
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(false);
        urlConnection.setConnectTimeout(DOWNLOAD_CONNECT_TIMEOUT);
        urlConnection.setReadTimeout(DOWNLOAD_READ_TIMEOUT);
        urlConnection.setRequestProperty("Connection", "Keep-Alive");
        urlConnection.setRequestProperty("Charset", "UTF-8");
        urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
        urlConnection.connect();
        int status = urlConnection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            return false;
        }
        int bytetotal = (int) urlConnection.getContentLength();
        int bytesum = 0;
        int byteread = 0;
        out = new BufferedOutputStream(new FileOutputStream(file));
        InputStream is = urlConnection.getInputStream();
        String content_encode = urlConnection.getContentEncoding();
        if (!TextUtils.isEmpty(content_encode) && content_encode.equals("gzip")) {
            is = new GZIPInputStream(is);
        }
        in = new BufferedInputStream(is);
        final Thread thread = Thread.currentThread();
        byte[] buffer = new byte[1444];
        while ((byteread = in.read(buffer)) != -1) {
            if (thread.isInterrupted()) {
                if (((float) bytesum / (float) bytetotal) < 0.8f) {
                    file.delete();
                    throw new InterruptedIOException();
                }
            }
            bytesum += byteread;
            out.write(buffer, 0, byteread);
            if (downloadListener != null && bytetotal > 0) {
                downloadListener.pushProgress(bytesum, bytetotal);
            }
        }
        if (downloadListener != null) {
            downloadListener.completed();
        }
        AppLogger.v("download request= " + urlStr + " download finished");
        result = true;
    } catch (IOException e) {
        e.printStackTrace();
        AppLogger.v("download request= " + urlStr + " download failed");
    } finally {
        Utility.closeSilently(in);
        Utility.closeSilently(out);
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    return result && ImageUtility.isThisBitmapCanRead(path);
}
Also used : InterruptedIOException(java.io.InterruptedIOException) GZIPInputStream(java.util.zip.GZIPInputStream) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) URL(java.net.URL) GZIPInputStream(java.util.zip.GZIPInputStream) Proxy(java.net.Proxy) HttpURLConnection(java.net.HttpURLConnection) BufferedInputStream(java.io.BufferedInputStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Example 92 with Proxy

use of java.net.Proxy in project weiciyuan by qii.

the class JavaHttpUtility method doPost.

public String doPost(String urlAddress, Map<String, String> param) throws WeiboException {
    GlobalContext globalContext = GlobalContext.getInstance();
    String errorStr = globalContext.getString(R.string.timeout);
    globalContext = null;
    try {
        URL url = new URL(urlAddress);
        Proxy proxy = getProxy();
        HttpsURLConnection uRLConnection;
        if (proxy != null) {
            uRLConnection = (HttpsURLConnection) url.openConnection(proxy);
        } else {
            uRLConnection = (HttpsURLConnection) url.openConnection();
        }
        uRLConnection.setDoInput(true);
        uRLConnection.setDoOutput(true);
        uRLConnection.setRequestMethod("POST");
        uRLConnection.setUseCaches(false);
        uRLConnection.setConnectTimeout(CONNECT_TIMEOUT);
        uRLConnection.setReadTimeout(READ_TIMEOUT);
        uRLConnection.setInstanceFollowRedirects(false);
        uRLConnection.setRequestProperty("Connection", "Keep-Alive");
        uRLConnection.setRequestProperty("Charset", "UTF-8");
        uRLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
        uRLConnection.connect();
        DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());
        out.write(Utility.encodeUrl(param).getBytes());
        out.flush();
        out.close();
        return handleResponse(uRLConnection);
    } catch (IOException e) {
        e.printStackTrace();
        throw new WeiboException(errorStr, e);
    }
}
Also used : GlobalContext(org.qii.weiciyuan.support.utils.GlobalContext) Proxy(java.net.Proxy) WeiboException(org.qii.weiciyuan.support.error.WeiboException) DataOutputStream(java.io.DataOutputStream) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 93 with Proxy

use of java.net.Proxy in project robovm by robovm.

the class ProxySelectorRoutePlanner method determineProxy.

/**
     * Determines a proxy for the given target.
     *
     * @param target    the planned target, never <code>null</code>
     * @param request   the request to be sent, never <code>null</code>
     * @param context   the context, or <code>null</code>
     *
     * @return  the proxy to use, or <code>null</code> for a direct route
     *
     * @throws HttpException
     *         in case of system proxy settings that cannot be handled
     */
protected HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) throws HttpException {
    // the proxy selector can be 'unset', so we better deal with null here
    ProxySelector psel = this.proxySelector;
    if (psel == null)
        psel = ProxySelector.getDefault();
    if (psel == null)
        return null;
    URI targetURI = null;
    try {
        targetURI = new URI(target.toURI());
    } catch (URISyntaxException usx) {
        throw new HttpException("Cannot convert host to URI: " + target, usx);
    }
    List<Proxy> proxies = psel.select(targetURI);
    Proxy p = chooseProxy(proxies, target, request, context);
    HttpHost result = null;
    if (p.type() == Proxy.Type.HTTP) {
        // convert the socket address to an HttpHost
        if (!(p.address() instanceof InetSocketAddress)) {
            throw new HttpException("Unable to handle non-Inet proxy address: " + p.address());
        }
        final InetSocketAddress isa = (InetSocketAddress) p.address();
        // assume default scheme (http)
        result = new HttpHost(getHost(isa), isa.getPort());
    }
    return result;
}
Also used : ProxySelector(java.net.ProxySelector) Proxy(java.net.Proxy) HttpHost(org.apache.http.HttpHost) InetSocketAddress(java.net.InetSocketAddress) HttpException(org.apache.http.HttpException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Example 94 with Proxy

use of java.net.Proxy in project robovm by robovm.

the class HttpURLConnectionImpl method processResponseHeaders.

/**
   * Returns the retry action to take for the current response headers. The
   * headers, proxy and target URL or this connection may be adjusted to
   * prepare for a follow up request.
   */
private Retry processResponseHeaders() throws IOException {
    Proxy selectedProxy = httpEngine.connection != null ? httpEngine.connection.getRoute().getProxy() : client.getProxy();
    final int responseCode = getResponseCode();
    switch(responseCode) {
        case HTTP_PROXY_AUTH:
            if (selectedProxy.type() != Proxy.Type.HTTP) {
                throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
            }
        // fall-through
        case HTTP_UNAUTHORIZED:
            boolean credentialsFound = HttpAuthenticator.processAuthHeader(client.getAuthenticator(), getResponseCode(), httpEngine.getResponseHeaders().getHeaders(), rawRequestHeaders, selectedProxy, url);
            return credentialsFound ? Retry.SAME_CONNECTION : Retry.NONE;
        case HTTP_MULT_CHOICE:
        case HTTP_MOVED_PERM:
        case HTTP_MOVED_TEMP:
        case HTTP_SEE_OTHER:
        case HTTP_TEMP_REDIRECT:
            if (!getInstanceFollowRedirects()) {
                return Retry.NONE;
            }
            if (++redirectionCount > MAX_REDIRECTS) {
                throw new ProtocolException("Too many redirects: " + redirectionCount);
            }
            if (responseCode == HTTP_TEMP_REDIRECT && !method.equals("GET") && !method.equals("HEAD")) {
                // the user agent MUST NOT automatically redirect the request"
                return Retry.NONE;
            }
            String location = getHeaderField("Location");
            if (location == null) {
                return Retry.NONE;
            }
            URL previousUrl = url;
            url = new URL(previousUrl, location);
            if (!url.getProtocol().equals("https") && !url.getProtocol().equals("http")) {
                // Don't follow redirects to unsupported protocols.
                return Retry.NONE;
            }
            boolean sameProtocol = previousUrl.getProtocol().equals(url.getProtocol());
            if (!sameProtocol && !client.getFollowProtocolRedirects()) {
                // This client doesn't follow redirects across protocols.
                return Retry.NONE;
            }
            boolean sameHost = previousUrl.getHost().equals(url.getHost());
            boolean samePort = getEffectivePort(previousUrl) == getEffectivePort(url);
            if (sameHost && samePort && sameProtocol) {
                return Retry.SAME_CONNECTION;
            } else {
                return Retry.DIFFERENT_CONNECTION;
            }
        default:
            return Retry.NONE;
    }
}
Also used : ProtocolException(java.net.ProtocolException) Proxy(java.net.Proxy) URL(java.net.URL)

Example 95 with Proxy

use of java.net.Proxy in project robovm by robovm.

the class OldSocketTest method test_bindLjava_net_SocketAddress_Proxy.

public void test_bindLjava_net_SocketAddress_Proxy() throws IOException {
    //The Proxy will not impact on the bind operation.It can be assigned with any address.
    Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 0));
    Socket socket = new Socket(proxy);
    try {
        InetAddress address = InetAddress.getByName("localhost");
        int port = 0;
        socket.bind(new InetSocketAddress(address, port));
        assertEquals(address, socket.getLocalAddress());
        assertTrue(port != socket.getLocalPort());
    } finally {
        socket.close();
    }
}
Also used : Proxy(java.net.Proxy) InetSocketAddress(java.net.InetSocketAddress) InetAddress(java.net.InetAddress) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket)

Aggregations

Proxy (java.net.Proxy)132 InetSocketAddress (java.net.InetSocketAddress)71 URL (java.net.URL)44 IOException (java.io.IOException)35 Test (org.junit.Test)22 URI (java.net.URI)21 ProxySelector (java.net.ProxySelector)20 HttpURLConnection (java.net.HttpURLConnection)19 SocketAddress (java.net.SocketAddress)19 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)13 URISyntaxException (java.net.URISyntaxException)11 ServerSocket (java.net.ServerSocket)10 Socket (java.net.Socket)9 PasswordAuthentication (java.net.PasswordAuthentication)8 InterruptedIOException (java.io.InterruptedIOException)6 URLConnection (java.net.URLConnection)6 SSLServerSocket (javax.net.ssl.SSLServerSocket)6 List (java.util.List)5 SSLSocket (javax.net.ssl.SSLSocket)5 OkHttpClient (okhttp3.OkHttpClient)5