Example usage for java.net Proxy address

List of usage examples for java.net Proxy address

Introduction

In this page you can find the example usage for java.net Proxy address.

Prototype

public SocketAddress address() 

Source Link

Document

Returns the socket address of the proxy, or null if its a direct connection.

Usage

From source file:jp.ne.sakura.kkkon.java.net.inetaddress.testapp.android.NetworkConnectionCheckerTestApp.java

/** Called when the activity is first created. */
@Override//from w  ww  . ja  va 2s .  co m
public void onCreate(Bundle savedInstanceState) {
    final Context context = this.getApplicationContext();

    {
        NetworkConnectionChecker.initialize();
    }

    super.onCreate(savedInstanceState);

    /* Create a TextView and set its content.
     * the text is retrieved by calling a native
     * function.
     */
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    TextView tv = new TextView(this);
    tv.setText("reachable=");
    layout.addView(tv);
    this.textView = tv;

    Button btn1 = new Button(this);
    btn1.setText("invoke Exception");
    btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            final int count = 2;
            int[] array = new int[count];
            int value = array[count]; // invoke IndexOutOfBOundsException
        }
    });
    layout.addView(btn1);

    {
        Button btn = new Button(this);
        btn.setText("disp isReachable");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                final boolean isReachable = NetworkConnectionChecker.isReachable();
                Toast toast = Toast.makeText(context, "IsReachable=" + isReachable, Toast.LENGTH_LONG);
                toast.show();
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("upload http AsyncTask");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() {

                    @Override
                    protected Boolean doInBackground(String... paramss) {
                        Boolean result = true;
                        Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid());
                        try {
                            //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
                            Log.d(TAG, "fng=" + Build.FINGERPRINT);
                            final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
                            list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

                            HttpPost httpPost = new HttpPost(paramss[0]);
                            //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                            httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                            DefaultHttpClient httpClient = new DefaultHttpClient();
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                                    new Integer(5 * 1000));
                            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                                    new Integer(5 * 1000));
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            // <uses-permission android:name="android.permission.INTERNET"/>
                            // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                            HttpResponse response = httpClient.execute(httpPost);
                            Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
                        } catch (Exception e) {
                            Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
                            result = false;
                        }
                        Log.d(TAG, "upload finish");
                        return result;
                    }

                };

                asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug");
                asyncTask.isCancelled();
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(0.0.0.0)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            destHost = InetAddress.getByName("0.0.0.0");
                            if (null != destHost) {
                                try {
                                    if (destHost.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " reachable");
                                    } else {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " not reachable");
                                    }
                                } catch (IOException e) {

                                }
                            }
                        } catch (UnknownHostException e) {

                        }
                        Log.d(TAG, "destHost=" + destHost);
                    }
                });
                thread.start();
                try {
                    thread.join(1000);
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }
    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(www.google.com)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        Log.d(TAG, "start");
                        try {
                            InetAddress dest = InetAddress.getByName("www.google.com");
                            if (null == dest) {
                                dest = destHost;
                            }

                            if (null != dest) {
                                final String[] uris = new String[] { "http://www.google.com/",
                                        "https://www.google.com/" };
                                for (final String destURI : uris) {
                                    URI uri = null;
                                    try {
                                        uri = new URI(destURI);
                                    } catch (URISyntaxException e) {
                                        //Log.d( TAG, e.toString() );
                                    }

                                    if (null != uri) {
                                        URL url = null;
                                        try {
                                            url = uri.toURL();
                                        } catch (MalformedURLException ex) {
                                            Log.d(TAG, "got exception:" + ex.toString(), ex);
                                        }

                                        URLConnection conn = null;
                                        if (null != url) {
                                            Log.d(TAG, "openConnection before");
                                            try {
                                                conn = url.openConnection();
                                                if (null != conn) {
                                                    conn.setConnectTimeout(3 * 1000);
                                                    conn.setReadTimeout(3 * 1000);
                                                }
                                            } catch (IOException e) {
                                                //Log.d( TAG, "got Exception" + e.toString(), e );
                                            }
                                            Log.d(TAG, "openConnection after");
                                            if (conn instanceof HttpURLConnection) {
                                                HttpURLConnection httpConn = (HttpURLConnection) conn;
                                                int responceCode = -1;
                                                try {
                                                    Log.d(TAG, "getResponceCode before");
                                                    responceCode = httpConn.getResponseCode();
                                                    Log.d(TAG, "getResponceCode after");
                                                } catch (IOException ex) {
                                                    Log.d(TAG, "got exception:" + ex.toString(), ex);
                                                }
                                                Log.d(TAG, "responceCode=" + responceCode);
                                                if (0 < responceCode) {
                                                    isReachable = true;
                                                    destHost = dest;
                                                }
                                                Log.d(TAG,
                                                        " HTTP ContentLength=" + httpConn.getContentLength());
                                                httpConn.disconnect();
                                                Log.d(TAG,
                                                        " HTTP ContentLength=" + httpConn.getContentLength());
                                            }
                                        }
                                    } // if uri

                                    if (isReachable) {
                                        //break;
                                    }
                                } // for uris
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                        Log.d(TAG, "end");
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(kkkon.sakura.ne.jp)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        Log.d(TAG, "start");
                        try {
                            InetAddress dest = InetAddress.getByName("kkkon.sakura.ne.jp");
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                    }
                                    destHost = dest;
                                } catch (IOException e) {

                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                        Log.d(TAG, "end");
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(kkkon.sakura.ne.jp) support proxy");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            String target = null;
                            {
                                ProxySelector proxySelector = ProxySelector.getDefault();
                                Log.d(TAG, "proxySelector=" + proxySelector);
                                if (null != proxySelector) {
                                    URI uri = null;
                                    try {
                                        uri = new URI("http://www.google.com/");
                                    } catch (URISyntaxException e) {
                                        Log.d(TAG, e.toString());
                                    }
                                    List<Proxy> proxies = proxySelector.select(uri);
                                    if (null != proxies) {
                                        for (final Proxy proxy : proxies) {
                                            Log.d(TAG, " proxy=" + proxy);
                                            if (null != proxy) {
                                                if (Proxy.Type.HTTP == proxy.type()) {
                                                    final SocketAddress sa = proxy.address();
                                                    if (sa instanceof InetSocketAddress) {
                                                        final InetSocketAddress isa = (InetSocketAddress) sa;
                                                        target = isa.getHostName();
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (null == target) {
                                target = "kkkon.sakura.ne.jp";
                            }
                            InetAddress dest = InetAddress.getByName(target);
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                        {
                                            ProxySelector proxySelector = ProxySelector.getDefault();
                                            //Log.d( TAG, "proxySelector=" + proxySelector );
                                            if (null != proxySelector) {
                                                URI uri = null;
                                                try {
                                                    uri = new URI("http://www.google.com/");
                                                } catch (URISyntaxException e) {
                                                    //Log.d( TAG, e.toString() );
                                                }

                                                if (null != uri) {
                                                    List<Proxy> proxies = proxySelector.select(uri);
                                                    if (null != proxies) {
                                                        for (final Proxy proxy : proxies) {
                                                            //Log.d( TAG, " proxy=" + proxy );
                                                            if (null != proxy) {
                                                                if (Proxy.Type.HTTP == proxy.type()) {
                                                                    URL url = uri.toURL();
                                                                    URLConnection conn = null;
                                                                    if (null != url) {
                                                                        try {
                                                                            conn = url.openConnection(proxy);
                                                                            if (null != conn) {
                                                                                conn.setConnectTimeout(
                                                                                        3 * 1000);
                                                                                conn.setReadTimeout(3 * 1000);
                                                                            }
                                                                        } catch (IOException e) {
                                                                            Log.d(TAG, "got Exception"
                                                                                    + e.toString(), e);
                                                                        }
                                                                        if (conn instanceof HttpURLConnection) {
                                                                            HttpURLConnection httpConn = (HttpURLConnection) conn;
                                                                            if (0 < httpConn
                                                                                    .getResponseCode()) {
                                                                                isReachable = true;
                                                                            }
                                                                            Log.d(TAG, " HTTP ContentLength="
                                                                                    + httpConn
                                                                                            .getContentLength());
                                                                            Log.d(TAG, " HTTP res=" + httpConn
                                                                                    .getResponseCode());
                                                                            //httpConn.setInstanceFollowRedirects( false );
                                                                            //httpConn.setRequestMethod( "HEAD" );
                                                                            //conn.connect();
                                                                            httpConn.disconnect();
                                                                            Log.d(TAG, " HTTP ContentLength="
                                                                                    + httpConn
                                                                                            .getContentLength());
                                                                            Log.d(TAG, " HTTP res=" + httpConn
                                                                                    .getResponseCode());
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                    }
                                    destHost = dest;
                                } catch (IOException e) {
                                    Log.d(TAG, "got Excpetion " + e.toString());
                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    setContentView(layout);
}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * Proxy???/*from www .  j a va 2  s  . co  m*/
 * 
 * @param proxy
 *            Proxy
 * @param url
 */
public static long testProxy(Proxy proxy, URL url, int ctimeout, int rtimeout, int testTimes) {
    if (proxy == null)
        return -1;
    if (url == null) {
        try {
            url = new URL(DEFAULT_TEST_PROXY_URL);
        } catch (MalformedURLException e1) {
            LOG.warn("[testProxy] illegal url -> {}", url);
            return -1;
        }
    }
    HttpURLConnection conn = null;
    try {
        StopWatch watch = new StopWatch();
        watch.start();
        conn = (HttpURLConnection) url.openConnection(proxy);
        if (ctimeout > 0)
            conn.setConnectTimeout(ctimeout);
        if (rtimeout > 0)
            conn.setReadTimeout(rtimeout);
        long available = conn.getInputStream().available(); // try to get input
        int code = conn.getResponseCode();
        if (available < 1 || code != 200)
            return -1; //no content get
        watch.stop();
        return watch.getTime();
    } catch (Exception e) {
        LOG.warn("[testProxy] Could not connect to proxy -> {}", proxy.address());
        if (testTimes > 0)
            return testProxy(proxy, url, ctimeout, rtimeout, testTimes - 1);
    } finally {
        if (conn != null)
            IOUtils.close(conn);
    }
    return -1;
}

From source file:com.xmlcalabash.library.HttpRequest.java

public void gorun() throws SaxonApiException {
    super.gorun();

    XdmNode requestDoc = source.read(stepContext);
    XdmNode start = S9apiUtils.getDocumentElement(requestDoc);

    if (!c_request.equals(start.getNodeName())) {
        throw XProcException.stepError(40);
    }/*  w  w w  . j a  v  a  2 s .co m*/

    // Check for valid attributes
    XdmSequenceIterator iter = start.axisIterator(Axis.ATTRIBUTE);
    boolean ok = true;
    while (iter.hasNext()) {
        XdmNode attr = (XdmNode) iter.next();
        QName name = attr.getNodeName();
        if (_method.equals(name) || _href.equals(name) || _detailed.equals(name) || _status_only.equals(name)
                || _username.equals(name) || _password.equals(name) || _auth_method.equals(name)
                || _send_authorization.equals(name) || _override_content_type.equals(name)) {
            // nop
        } else {
            if (XMLConstants.DEFAULT_NS_PREFIX.equals(name.getNamespaceURI())) {
                throw new XProcException(step.getNode(),
                        "Unsupported attribute on c:request for p:http-request: " + name);
            }
        }
    }

    String send = step.getExtensionAttribute(cx_send_binary);
    encodeBinary = !"true".equals(send);

    method = start.getAttributeValue(_method);
    statusOnly = "true".equals(start.getAttributeValue(_status_only));
    detailed = "true".equals(start.getAttributeValue(_detailed));
    overrideContentType = start.getAttributeValue(_override_content_type);

    if (method == null) {
        throw XProcException.stepError(6);
    }

    if (statusOnly && !detailed) {
        throw XProcException.stepError(4);
    }

    if (start.getAttributeValue(_href) == null) {
        throw new XProcException(step.getNode(),
                "The 'href' attribute must be specified on c:request for p:http-request");
    }

    requestURI = start.getBaseURI().resolve(start.getAttributeValue(_href));

    if ("file".equals(requestURI.getScheme())) {
        doFile();
        return;
    }

    // What about cookies
    String saveCookieKey = step.getExtensionAttribute(cx_save_cookies);
    String useCookieKeys = step.getExtensionAttribute(cx_use_cookies);
    String cookieKey = step.getExtensionAttribute(cx_cookies);

    if (saveCookieKey == null) {
        saveCookieKey = cookieKey;
    }

    if (useCookieKeys == null) {
        useCookieKeys = cookieKey;
    }

    client = new HttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    client.getParams().setParameter("http.protocol.single-cookie-header", true);

    HttpState state = client.getState();

    if (useCookieKeys != null) {
        for (String key : useCookieKeys.split("\\s+")) {
            for (Cookie cookie : runtime.getCookies(key)) {
                state.addCookie(cookie);
            }
        }
    }

    String timeOutStr = step.getExtensionAttribute(cx_timeout);
    if (timeOutStr != null) {
        HttpMethodParams params = client.getParams();
        params.setSoTimeout(Integer.parseInt(timeOutStr));
    }

    ProxySelector proxySelector = ProxySelector.getDefault();
    List<Proxy> plist = proxySelector.select(requestURI);
    // I have no idea what I'm expected to do if I get more than one...
    if (plist.size() > 0) {
        Proxy proxy = plist.get(0);
        switch (proxy.type()) {
        case DIRECT:
            // nop;
            break;
        case HTTP:
            // This can't cause a ClassCastException, right?
            InetSocketAddress addr = (InetSocketAddress) proxy.address();
            String host = addr.getHostName();
            int port = addr.getPort();
            client.getHostConfiguration().setProxy(host, port);
            break;
        default:
            // FIXME: send out a log message
            break;
        }
    }

    if (start.getAttributeValue(_username) != null) {
        String user = start.getAttributeValue(_username);
        String pass = start.getAttributeValue(_password);
        String meth = start.getAttributeValue(_auth_method);

        if (meth == null || !("basic".equals(meth.toLowerCase()) || "digest".equals(meth.toLowerCase()))) {
            throw XProcException.stepError(3, "Unsupported auth-method: " + meth);
        }

        String host = requestURI.getHost();
        int port = requestURI.getPort();
        AuthScope scope = new AuthScope(host, port);

        UsernamePasswordCredentials cred = new UsernamePasswordCredentials(user, pass);

        client.getState().setCredentials(scope, cred);

        if ("basic".equals(meth.toLowerCase())) {
            client.getParams().setAuthenticationPreemptive(true);
        }
    }

    iter = start.axisIterator(Axis.CHILD);
    XdmNode body = null;
    while (iter.hasNext()) {
        XdmNode event = (XdmNode) iter.next();
        // FIXME: What about non-whitespace text nodes?
        if (event.getNodeKind() == XdmNodeKind.ELEMENT) {
            if (body != null) {
                throw new UnsupportedOperationException("Elements follow c:multipart or c:body");
            }

            if (XProcConstants.c_header.equals(event.getNodeName())) {
                String name = event.getAttributeValue(_name);
                if (name == null) {
                    continue; // this can't happen, right?
                }
                if (name.toLowerCase().equals("content-type")) {
                    // We'll deal with the content-type header later
                    headerContentType = event.getAttributeValue(_value).toLowerCase();
                } else {
                    headers.add(new Header(event.getAttributeValue(_name), event.getAttributeValue(_value)));
                }
            } else if (XProcConstants.c_multipart.equals(event.getNodeName())
                    || XProcConstants.c_body.equals(event.getNodeName())) {
                body = event;
            } else {
                throw new UnsupportedOperationException("Unexpected request element: " + event.getNodeName());
            }
        }
    }

    String lcMethod = method.toLowerCase();

    // You can only have a body on PUT or POST
    if (body != null && !("put".equals(lcMethod) || "post".equals(lcMethod))) {
        throw XProcException.stepError(5);
    }

    HttpMethodBase httpResult;

    if ("get".equals(lcMethod)) {
        httpResult = doGet();
    } else if ("post".equals(lcMethod)) {
        httpResult = doPost(body);
    } else if ("put".equals(lcMethod)) {
        httpResult = doPut(body);
    } else if ("head".equals(lcMethod)) {
        httpResult = doHead();
    } else if ("delete".equals(lcMethod)) {
        httpResult = doDelete();
    } else {
        throw new UnsupportedOperationException("Unrecognized http method: " + method);
    }

    TreeWriter tree = new TreeWriter(runtime);
    tree.startDocument(requestURI);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(httpResult);

        // Deal with cookies
        if (saveCookieKey != null) {
            runtime.clearCookies(saveCookieKey);

            state = client.getState();
            Cookie[] cookies = state.getCookies();
            for (Cookie cookie : cookies) {
                runtime.addCookie(saveCookieKey, cookie);
            }
        }

        String contentType = getContentType(httpResult);
        if (overrideContentType != null) {
            if ((xmlContentType(contentType) && overrideContentType.startsWith("image/"))
                    || (contentType.startsWith("text/") && overrideContentType.startsWith("image/"))
                    || (contentType.startsWith("image/") && xmlContentType(overrideContentType))
                    || (contentType.startsWith("image/") && overrideContentType.startsWith("text/"))
                    || (contentType.startsWith("multipart/") && !overrideContentType.startsWith("multipart/"))
                    || (!contentType.startsWith("multipart/")
                            && overrideContentType.startsWith("multipart/"))) {
                throw XProcException.stepError(30);
            }

            //System.err.println(overrideContentType + " overrides " + contentType);
            contentType = overrideContentType;
        }

        if (detailed) {
            tree.addStartElement(XProcConstants.c_response);
            tree.addAttribute(_status, "" + statusCode);
            tree.startContent();

            for (Header header : httpResult.getResponseHeaders()) {
                // I don't understand why/how HeaderElement parsing works. I get very weird results.
                // So I'm just going to go the long way around...
                String h = header.toString();
                int cp = h.indexOf(":");
                String name = header.getName();
                String value = h.substring(cp + 1).trim();

                tree.addStartElement(XProcConstants.c_header);
                tree.addAttribute(_name, name);
                tree.addAttribute(_value, value);
                tree.startContent();
                tree.addEndElement();
            }

            if (statusOnly) {
                // Skip reading the result
            } else {
                // Read the response body.
                InputStream bodyStream = httpResult.getResponseBodyAsStream();
                if (bodyStream != null) {
                    readBodyContent(tree, bodyStream, httpResult);
                }
            }

            tree.addEndElement();
        } else {
            if (statusOnly) {
                // Skip reading the result
            } else {
                // Read the response body.
                InputStream bodyStream = httpResult.getResponseBodyAsStream();
                if (bodyStream != null) {
                    readBodyContent(tree, bodyStream, httpResult);
                } else {
                    throw XProcException.dynamicError(6);
                }
            }
        }
    } catch (Exception e) {
        throw new XProcException(e);
    } finally {
        // Release the connection.
        httpResult.releaseConnection();
    }

    tree.endDocument();

    XdmNode resultNode = tree.getResult();

    result.write(stepContext, resultNode);
}

From source file:nz.dataview.websyncclientgui.WebSYNCClientGUIView.java

/**
 * try to detect if a proxy exists, and update the UI
 * //from w w  w  . j  av a  2 s  . c  o  m
 * @return
 */
private void detectProxy() {

    try {
        proxyDetectedLabel.setText("");
        List l = ProxySelector.getDefault().select(new URI(knURLField.getText()));

        for (Iterator iter = l.iterator(); iter.hasNext();) {
            Proxy proxy = (Proxy) iter.next();
            if ("DIRECT".equals(proxy.type().toString())) {
                proxyEnabled = false;
                useProxyField.setSelected(proxyEnabled);
                proxyFieldsUpdate(proxyEnabled);
            } else {
                InetSocketAddress addr = (InetSocketAddress) proxy.address();
                if (addr != null) {
                    // if we have a proxy set the correct fields and state of UI
                    proxyEnabled = true;
                    useProxyField.setSelected(proxyEnabled);
                    proxyHostField.setText(addr.getHostName());
                    proxyPortField.setText(Integer.toString(addr.getPort()));
                    proxyFieldsUpdate(proxyEnabled);

                }
            }
            String text = (String) "Proxy settings detected and updated";
            proxyDetectedLabel.setText(text);
        }
    } catch (Exception e) {
        showErrorDialog("Detect Proxy", "Problem in detecting proxy, please set proxy settings manually");
    }

}

From source file:com.dwdesign.tweetings.util.Utils.java

public static HttpClientWrapper getHttpClient(final int timeout_millis, final boolean ignore_ssl_error,
        final Proxy proxy, final HostAddressResolver resolver, final String user_agent) {
    final ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setHttpConnectionTimeout(timeout_millis);
    if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        final SocketAddress address = proxy.address();
        if (address instanceof InetSocketAddress) {
            cb.setHttpProxyHost(((InetSocketAddress) address).getHostName());
            cb.setHttpProxyPort(((InetSocketAddress) address).getPort());
        }/*w  ww . j a va 2 s. c o m*/
    }
    // cb.setHttpClientImplementation(HttpClientImpl.class);
    return new HttpClientWrapper(cb.build());
}

From source file:org.mariotaku.twidere.util.Utils.java

public static HttpClientWrapper getHttpClient(final int timeout_millis, final boolean ignore_ssl_error,
        final Proxy proxy, final HostAddressResolver resolver, final String user_agent) {
    final ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setHttpConnectionTimeout(timeout_millis);
    cb.setIgnoreSSLError(ignore_ssl_error);
    if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        final SocketAddress address = proxy.address();
        if (address instanceof InetSocketAddress) {
            cb.setHttpProxyHost(((InetSocketAddress) address).getHostName());
            cb.setHttpProxyPort(((InetSocketAddress) address).getPort());
        }//  w w  w.  j  ava  2  s . c  o m
    }
    cb.setHostAddressResolver(resolver);
    if (user_agent != null) {
        cb.setUserAgent(user_agent);
    }
    // cb.setHttpClientImplementation(HttpClientImpl.class);
    return new HttpClientWrapper(cb.build());
}

From source file:de.vanita5.twittnuker.util.Utils.java

public static HttpClientWrapper getHttpClient(final Context context, final int timeoutMillis,
        final boolean ignoreSslError, final Proxy proxy, final HostAddressResolverFactory resolverFactory,
        final String userAgent, final boolean twitterClientHeader) {
    final ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setHttpConnectionTimeout(timeoutMillis);
    cb.setIgnoreSSLError(ignoreSslError);
    cb.setIncludeTwitterClientHeader(twitterClientHeader);
    if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        final SocketAddress address = proxy.address();
        if (address instanceof InetSocketAddress) {
            cb.setHttpProxyHost(((InetSocketAddress) address).getHostName());
            cb.setHttpProxyPort(((InetSocketAddress) address).getPort());
        }//from  ww  w  .j  a  v  a2s . c  o  m
    }
    cb.setHostAddressResolverFactory(resolverFactory);
    if (userAgent != null) {
        cb.setHttpUserAgent(userAgent);
    }
    cb.setHttpClientFactory(new TwidereHttpClientFactory(context));
    return new HttpClientWrapper(cb.build());
}

From source file:org.getlantern.firetweet.util.Utils.java

public static HttpClientWrapper getHttpClient(final Context context, final int timeoutMillis,
        final boolean ignoreSslError, final Proxy proxy, final HostAddressResolverFactory resolverFactory,
        final String userAgent, final boolean twitterClientHeader) {
    final ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setHttpConnectionTimeout(timeoutMillis);
    cb.setIgnoreSSLError(ignoreSslError);
    cb.setIncludeTwitterClientHeader(twitterClientHeader);
    if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        final SocketAddress address = proxy.address();
        if (address instanceof InetSocketAddress) {
            cb.setHttpProxyHost(((InetSocketAddress) address).getHostName());
            cb.setHttpProxyPort(((InetSocketAddress) address).getPort());
        }/*from   w  ww .j  av  a  2  s  .  c o  m*/
    }
    cb.setHostAddressResolverFactory(resolverFactory);
    if (userAgent != null) {
        cb.setHttpUserAgent(userAgent);
    }
    cb.setHttpClientFactory(new OkHttpClientFactory(context));
    return new HttpClientWrapper(cb.build());
}