Example usage for java.net URLConnection setRequestProperty

List of usage examples for java.net URLConnection setRequestProperty

Introduction

In this page you can find the example usage for java.net URLConnection setRequestProperty.

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:org.t3.metamediamanager.TheMovieDBProvider.java

/**
 * //from w ww.java  2s. c o m
 * @param s
 *       The query.
 * @param i
 * The way of your query :
 *          -s = general query (with the MovieTitle)
 *          -i = precise query (with the MovieId)
 * @param language
 *       The language in which one you want the informations.
 * @return A JSONObject which contains the data.
 * @throws ProviderException
 */
public JSONObject getJSON(String s, int i, String language) throws ProviderException {
    try {
        if (i == 'i') {
            //http://api.themoviedb.org/3/movie/550?api_key=ebb392e0588bc0b5ab9d9a6100711a8c
            query = String.format(
                    "http://api.themoviedb.org/3/movie/%s?api_key=ebb392e0588bc0b5ab9d9a6100711a8c&append_to_response=casts&language=%s",
                    URLEncoder.encode(s, charset), URLEncoder.encode(language, charset));
        } else if (i == 's') {
            query = String.format(
                    "http://api.themoviedb.org/3/search/movie?api_key=ebb392e0588bc0b5ab9d9a6100711a8c&query=%s",
                    URLEncoder.encode(s, charset));
        }
        URLConnection connection = new URL(query).openConnection();
        connection.setRequestProperty("Accept-Charset", charset);
        InputStream response = connection.getInputStream();
        String rep = convertStreamToString(response);
        return convertStringToJSON(rep);
    } catch (IOException e) {
        throw new ProviderException("Erreur d'accs  l'API !" + e.getMessage());
    }
}

From source file:com.liferay.ide.server.remote.RemoteLogStream.java

protected static InputStream openInputStream(IServerManagerConnection remote, URL url) throws IOException {
    String username = remote.getUsername();
    String password = remote.getPassword();

    String authString = username + ":" + password; //$NON-NLS-1$
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);
    final IProxyService proxyService = LiferayCore.getProxyService();
    URLConnection conn = null;

    try {/*from   w  ww .  j  av  a  2 s . c o  m*/
        URI uri = new URI("HTTP://" + url.getHost() + ":" + url.getPort()); //$NON-NLS-1$ //$NON-NLS-2$
        IProxyData[] proxyDataForHost = proxyService.select(uri);

        for (IProxyData data : proxyDataForHost) {
            if (data.getHost() != null) {
                System.setProperty("http.proxyHost", data.getHost()); //$NON-NLS-1$
                System.setProperty("http.proxyPort", String.valueOf(data.getPort())); //$NON-NLS-1$

                break;
            }
        }

        uri = new URI("SOCKS://" + url.getHost() + ":" + url.getPort()); //$NON-NLS-1$ //$NON-NLS-2$
        proxyDataForHost = proxyService.select(uri);

        for (IProxyData data : proxyDataForHost) {
            if (data.getHost() != null) {
                System.setProperty("socksProxyHost", data.getHost()); //$NON-NLS-1$
                System.setProperty("socksProxyPort", String.valueOf(data.getPort())); //$NON-NLS-1$

                break;
            }
        }
    } catch (URISyntaxException e) {
        LiferayServerCore.logError("Could not read proxy data", e); //$NON-NLS-1$
    }

    conn = url.openConnection();
    conn.setRequestProperty("Authorization", "Basic " + authStringEnc); //$NON-NLS-1$ //$NON-NLS-2$
    Authenticator.setDefault(null);
    conn.setAllowUserInteraction(false);

    return conn.getInputStream();
}

From source file:org.bbaw.telota.ediarum.ReadRegister.java

/**
 * Der Konstruktor liest das Dokument der URL mit den benannten Knoten aus und konstruiert den Eintrag und die Id fr jeden Knoten.
 * @param indexURI Die URL zur Registerdatei
 * @param node Der X-Path-Ausdruck fr die Knoten der einzelnen Registereintrge
 * @param eintragExp Der Ausdruck um einen Registereintrag zu konstruieren. Er setzt sich aus Strings in "", Attributen beginnend mit @,
 *  Elementen mit / oder // und aus X-Path-Ausdrcken beginnend mit . zusammen. Die einzelnen Teile werden mit + verbunden.
 * @param idExp Der Ausdruck um die ID fr einen Registereintrag zu konstruieren. Er setzt sich wie eintragExp zusammen.
 * @throws AuthorOperationException// w  w  w .jav  a 2s.com
 */
public ReadRegister(String indexURI, String node, String eintragExp, String idExp) {

    try {
        // Das neue Dokument wird vorbereitet.
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        DocumentBuilder builder = domFactory.newDocumentBuilder();

        // Wenn es sich um eine URL mit Authentifizierung handelt, ..
        InputStream is;
        if (indexURI.indexOf('@') > -1) {
            // .. werden die Verbindungsdaten gelesen ..
            String authString = indexURI.substring(indexURI.indexOf("://") + 3, indexURI.indexOf('@'));
            String webPage = indexURI.substring(0, indexURI.indexOf("://") + 3)
                    + indexURI.substring(indexURI.indexOf('@') + 1);
            byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
            String authStringEnc = new String(authEncBytes);

            // .. und eine Verbindung mit Login geffnet.
            URL url = new URL(webPage);
            URLConnection urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
            is = urlConnection.getInputStream();
        } else {
            // Im anderen Fall wird direkt eine Verbindung geffnet.
            URL url = new URL(indexURI);
            URLConnection urlConnection = url.openConnection();
            is = urlConnection.getInputStream();
        }

        // Dann wird die Datei gelesen.
        InputSource inputSource = new InputSource(is);
        Document indexDoc = builder.parse(inputSource);
        // Die xPath-Routinen werden vorbereitet.
        XPath xpath = XPathFactory.newInstance().newXPath();
        // Das XPath-Query wird definiert.
        XPathExpression expr = xpath.compile(node);

        // Die Resultate werden ausgelesen..
        Object result = expr.evaluate(indexDoc, XPathConstants.NODESET);
        NodeList registerNodes = (NodeList) result;

        // .. dann werden fr die Eintrge und IDs entsprechend lange Arrays angelegt.
        eintrag = new String[registerNodes.getLength()];
        id = new String[registerNodes.getLength()];

        // Die Ausdrcke fr die Eintrge ..
        String[] eintragExpression = (eintragExp).split("[+]");
        for (int i = 0; i < eintragExpression.length; i++) {
            eintragExpression[i] = eintragExpression[i].trim();
        }
        // .. und IDs werden in einzelne Glieder geteilt. 
        String[] idExpression = (idExp).split("[+]");
        for (int i = 0; i < idExpression.length; i++) {
            idExpression[i] = idExpression[i].trim();
        }

        // Fr jeden Knoten ..
        for (int i = 0; i < registerNodes.getLength(); i++) {
            Element currentElement = (Element) registerNodes.item(i);
            // .. wird der Eintrag konstruiert.
            eintrag[i] = "";
            // Dazu werden die Glieder des entsprechenden Ausdrucks interpretiert.
            for (int j = 0; j < eintragExpression.length; j++) {
                try {
                    // Jedes Glied kann entweder als Attribut, ..
                    if (eintragExpression[j].startsWith("@")) {
                        String attributeName = eintragExpression[j].substring(1);
                        eintrag[i] += currentElement.getAttribute(attributeName);
                    }
                    // .. als String, ..
                    if (eintragExpression[j].startsWith("\"") && eintragExpression[j].endsWith("\"")) {
                        String stringexpression = eintragExpression[j].substring(1,
                                eintragExpression[j].length() - 1);
                        eintrag[i] += stringexpression;
                    }
                    // .. als spter zu verarbeitetende Variable, ..
                    if (eintragExpression[j].startsWith("$")) {
                        String stringexpression = eintragExpression[j];
                        eintrag[i] += stringexpression;
                    }
                    // **
                    // .. als nachkommendes Element ..
                    if (eintragExpression[j].startsWith("//")) {
                        // .. (was direkt gelesen werden kann und schnell geht, ..
                        String elementName = eintragExpression[j].substring(2);
                        if (currentElement.getElementsByTagName(elementName).getLength() > 0) {
                            eintrag[i] += currentElement.getElementsByTagName(elementName).item(0)
                                    .getTextContent();
                        } else {
                            // .. oder welches ber eine X-Path-Abfrage gelesen werden kann und lange dauert), ..
                            XPathExpression queryExpr = xpath.compile("." + eintragExpression[j]);
                            NodeList elementNodes = (NodeList) queryExpr.evaluate(registerNodes.item(i),
                                    XPathConstants.NODESET);
                            if (elementNodes.getLength() > 0
                                    && elementNodes.item(0).getNodeType() == Node.ELEMENT_NODE) {
                                eintrag[i] += elementNodes.item(0).getTextContent();
                            }
                        }
                        // .. als direktes Kindelement (was schnell geht) ..
                    } else if (eintragExpression[j].startsWith("/")) {
                        String elementName = eintragExpression[j].substring(1);
                        if (currentElement.getElementsByTagName(elementName).getLength() > 0) {
                            eintrag[i] += currentElement.getElementsByTagName(elementName).item(0)
                                    .getTextContent();
                        }
                    }
                    // .. oder als X-Path-Ausdruck (was sehr lange dauert) verstanden werden.
                    if (eintragExpression[j].startsWith(".")) {
                        XPathExpression queryExpr = xpath.compile(eintragExpression[j]);
                        NodeList elementNodes = (NodeList) queryExpr.evaluate(registerNodes.item(i),
                                XPathConstants.NODESET);
                        if (elementNodes.item(0).getNodeType() == Node.ELEMENT_NODE) {
                            eintrag[i] += elementNodes.item(0).getTextContent();
                        }
                    }
                } catch (ArrayIndexOutOfBoundsException e) {
                }
            }

            // Genauso wird die ID konstruiert.
            id[i] = "";
            // Dazu werden die Glieder des entsprechenden Ausdrucks interpretiert.
            for (int j = 0; j < idExpression.length; j++) {
                try {
                    // Jedes Glied kann entweder als Attribut, ..
                    if (idExpression[j].startsWith("@")) {
                        String attributeName = idExpression[j].substring(1);
                        id[i] += currentElement.getAttribute(attributeName);
                    }
                    // .. als String, ..
                    if (idExpression[j].startsWith("\"") && idExpression[j].endsWith("\"")) {
                        String stringexpression = idExpression[j].substring(1, idExpression[j].length() - 1);
                        id[i] += stringexpression;
                    }
                    // .. als spter zu verarbeitetende Variable, ..
                    if (idExpression[j].startsWith("$")) {
                        String stringexpression = idExpression[j];
                        id[i] += stringexpression;
                    }
                    // .. als nachkommendes Element ..
                    if (idExpression[j].startsWith("//")) {
                        // .. (was direkt gelesen werden kann und schnell geht, ..
                        String elementName = idExpression[j].substring(2);
                        if (currentElement.getElementsByTagName(elementName).getLength() > 0) {
                            id[i] += currentElement.getElementsByTagName(elementName).item(0).getTextContent();
                        } else {
                            // .. oder welches ber eine X-Path-Abfrage gelesen werden kann und lange dauert), ..
                            XPathExpression queryExpr = xpath.compile("." + idExpression[j]);
                            NodeList elementNodes = (NodeList) queryExpr.evaluate(registerNodes.item(i),
                                    XPathConstants.NODESET);
                            if (elementNodes.getLength() > 0
                                    && elementNodes.item(0).getNodeType() == Node.ELEMENT_NODE) {
                                id[i] += elementNodes.item(0).getTextContent();
                            }
                        }
                        // .. als direktes Kindelement (was schnell geht) ..
                    } else if (idExpression[j].startsWith("/")) {
                        String elementName = idExpression[j].substring(1);
                        if (currentElement.getElementsByTagName(elementName).getLength() > 0) {
                            id[i] += currentElement.getElementsByTagName(elementName).item(0).getTextContent();
                        }
                    }
                    // .. oder als X-Path-Ausdruck (was sehr lange dauert) verstanden werden.
                    if (idExpression[j].startsWith(".")) {
                        XPathExpression queryExpr = xpath.compile(idExpression[j]);
                        NodeList elementNodes = (NodeList) queryExpr.evaluate(registerNodes.item(i),
                                XPathConstants.NODESET);
                        if (elementNodes.item(0).getNodeType() == Node.ELEMENT_NODE) {
                            id[i] += elementNodes.item(0).getTextContent();
                        }
                    }
                } catch (ArrayIndexOutOfBoundsException e) {
                }
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    } catch (DOMException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
}

From source file:org.infoglue.igide.helper.http.HTTPTextDocumentListenerEngine.java

private void listen() {
    String errorMessage;/*  w  ww .j av a 2s.  c o m*/
    boolean error;
    errorMessage = "";
    error = false;
    try {
        Logger.logConsole("Starting listen thread");
        URLConnection urlConn = url.openConnection();
        urlConn.setConnectTimeout(3000);
        urlConn.setRequestProperty("Connection", "Keep-Alive");
        urlConn.setReadTimeout(0);
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setAllowUserInteraction(false);
        if (urlConn.getHeaderFields().toString().indexOf("401 Unauthorized") > -1) {
            Logger.logConsole("User has no access to the CMS - closing connection");
            throw new AccessControlException("User has no access to the CMS - closing connection");
        }
        String boundary = urlConn.getHeaderField("boundary");
        DataInputStream input = new DataInputStream(urlConn.getInputStream());
        StringBuffer buf = new StringBuffer();
        if (listener != null)
            listener.onConnection(url);
        String str = null;
        while ((str = input.readLine()) != null) {
            if (str.indexOf("XMLNotificationWriter.ping") == -1) {
                if (str.equals(boundary)) {
                    String message = buf.toString();

                    // By checking there is more in the String than the XML declaration we assume the message is valid
                    if (message != null
                            && !message.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "").equals("")) {
                        if (listener != null)
                            listener.recieveDocument(buf.toString());
                        else
                            Logger.logConsole((new StringBuilder("NEW DOCUMENT!!\r\n")).append(buf.toString())
                                    .append("\r\n").toString());
                    }
                    buf = new StringBuffer();
                } else {
                    buf.append(str);
                }
            }
        }
        input.close();
    } catch (MalformedURLException me) {
        error = true;
        errorMessage = (new StringBuilder("Faulty CMS-url:")).append(url).toString();
        if (listener != null)
            listener.onException(me);
        else
            System.err.println((new StringBuilder("MalformedURLException: ")).append(me).toString());
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (IOException ioe) {
        error = true;
        errorMessage = "Got an I/O-Exception talking to the CMS. Check that it is started and in valid state.";
        Logger.logConsole((new StringBuilder("ioe: ")).append(ioe.getMessage()).toString());
        if (listener != null)
            listener.onException(ioe);
        else
            Logger.logConsole((new StringBuilder("TextDocumentListener cannot connect to: "))
                    .append(url.toExternalForm()).toString());
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (AccessControlException ace) {
        error = true;
        errorMessage = "The user you tried to connect with did not have the correct access rights. Check that he/she has roles etc enough to access the CMS";
        Logger.logConsole((new StringBuilder("ioe: ")).append(ace.getMessage()).toString());
        if (listener != null)
            listener.onException(ace);
        else
            Logger.logConsole((new StringBuilder()).append(ace.getMessage()).toString());
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (Exception exception) {
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (Throwable e) {
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e2) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e2.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    }
}

From source file:org.jab.docsearch.utils.NetUtils.java

/**
 * Gets URL size (content)/*from   w  w  w . j a  v a2s. co  m*/
 *
 * @param url  URL for connect
 * @return     size in bytes of a url or 0 if broken or timed out connection
 */
public long getURLSize(final String url) {
    try {
        URL tmpURL = new URL(url);
        URLConnection conn = tmpURL.openConnection();

        // set connection parameter
        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setUseCaches(false);
        conn.setRequestProperty("User-Agent", USER_AGENT);

        // connect
        conn.connect();

        long contentLength = conn.getContentLength();

        if (logger.isDebugEnabled()) {
            logger.debug("getURLSize() content lentgh=" + contentLength + " of URL='" + url + "'");
        }

        return contentLength;
    } catch (IOException ioe) {
        logger.error("getURLSize() failed for URL='" + url + "'", ioe);
        return 0;
    }
}

From source file:org.jab.docsearch.utils.NetUtils.java

/**
 * Gets URL modified date as long/*from w ww . ja v  a2  s  .  c o  m*/
 *
 * @param url  URL to connect
 * @return         date of URLs modification or 0 if an error occurs
 */
public long getURLModifiedDate(final String url) {
    try {
        URL tmpURL = new URL(url);
        URLConnection conn = tmpURL.openConnection();

        // set connection parameter
        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setUseCaches(false);
        conn.setRequestProperty("User-Agent", USER_AGENT);

        // connect
        conn.connect();

        long modifiedDate = conn.getLastModified();

        if (logger.isDebugEnabled()) {
            logger.debug("getURLModifiedDate() modified date=" + modifiedDate + " of URL='" + url + "'");
        }

        return modifiedDate;
    } catch (IOException ioe) {
        logger.error("getURLModifiedDate() failed for URL='" + url + "'", ioe);
        return 0;
    }
}

From source file:org.tt.core.fetch.lexx.LexxDataFetcher.java

/**
 * Parsing method. It is dedicated to be able to override it in the test method.
 * @param link The link to the SSU endpoint.
 * @return DOM-parsed XML file./*from   ww  w.ja  va 2 s .co  m*/
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 */
protected Document getDocFromURL(String link) throws IOException, SAXException, ParserConfigurationException {
    DocumentBuilder builder = factory.newDocumentBuilder();
    URL url;
    URLConnection conn = null;
    try {
        url = new URL(link);
        conn = url.openConnection();
        String encoded = Base64.encodeBase64String(StringUtils.getBytesUtf8(loginPassword));
        conn.setRequestProperty("Authorization", "Basic " + encoded);
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (conn != null) {
        return builder.parse(conn.getInputStream());
    } else
        throw new UnknownHostException();
}

From source file:edu.caltech.ipac.firefly.server.catquery.SDSSQuery.java

@Override
protected File loadDataFile(TableServerRequest request) throws IOException, DataAccessException {

    File outFile;/*from  ww  w  .  j  av a  2 s  . com*/
    try {
        // votable has utf-16 encoding, which mismatches the returned content type
        // this confuses tools
        File csv = createFile(request, ".csv");
        String uploadFname = request.getParam(SDSSRequest.FILE_NAME);
        if (StringUtils.isEmpty(uploadFname)) {

            URL url = createGetURL(request);

            URLConnection conn = URLDownload.makeConnection(url);
            conn.setRequestProperty("Accept", "*/*");

            URLDownload.getDataToFile(conn, csv);
        } else {
            File uploadFile = ServerContext.convertToFile(uploadFname);
            File sdssUFile;
            if (uploadFile.canRead()) {
                sdssUFile = getSDSSUploadFile(uploadFile);
            } else {
                throw new EndUserException("SDSS catalog search failed",
                        "Can not read uploaded file: " + uploadFname);
            }

            URL url = new URL(SERVICE_URL_UPLOAD);
            // use uploadFname
            //POST http://skyserver.sdss3.org/public/en/tools/crossid/x_crossid.aspx

            _postBuilder = new MultiPartPostBuilder(url.toString());
            if (_postBuilder == null) {
                throw new EndUserException("Failed to create HTTP POST request", "URL " + SERVICE_URL_UPLOAD);
            }

            insertPostParams(request, sdssUFile);
            BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(csv), 10240);
            MultiPartPostBuilder.MultiPartRespnse resp = null;
            try {
                resp = _postBuilder.post(writer);
            } finally {
                writer.close();
            }

            if (resp == null) {
                throw new IOException("Exception during post");
            } else if (resp.getStatusCode() < 200 || resp.getStatusCode() > 300) {
                // throw new IOException(resp.getStatusMsg());
                // try repeating the request through CasJobs
                boolean nearestOnly = request.getBooleanParam(SDSSRequest.NEAREST_ONLY);
                String radiusArcMin = request.getParam(SDSSRequest.RADIUS_ARCMIN);
                SDSSCasJobs.getCrossMatchResults(sdssUFile, nearestOnly, radiusArcMin, csv);
            }
        }

        // check for errors in returned file
        evaluateCVS(csv);

        DataGroup dg = DsvToDataGroup.parse(csv, CSVFormat.DEFAULT.withCommentStart('#'));
        if (dg == null) {
            _log.briefInfo("no data found for search");
            return null;
        }

        /*
        //TG No need to decrement up_id, since we are using the original upload id
        if (!StringUtils.isEmpty(uploadFname) && dg.containsKey("up_id")) {
        // increment up_id(uploaded id) by 1 if it's an multi object search
        DataType upId = dg.getDataDefintion("up_id");
        for(DataObject row : dg) {
            int id = StringUtils.getInt(String.valueOf(row.getDataElement(upId)), -1);
            if (id >= 0) {
                row.setDataElement(upId, id + 1);
            }
        }
        }
        */

        outFile = createFile(request, ".tbl");
        IpacTableWriter.save(outFile, dg);

    } catch (MalformedURLException e) {
        _log.error(e, "Bad URL");
        throw makeException(e, "SDSS Catalog Query Failed - bad url");
    } catch (IOException e) {
        _log.error(e, e.toString());
        throw makeException(e, "SDSS Catalog Query Failed - network Error");
    } catch (EndUserException e) {
        _log.error(e, e.toString());
        throw makeException(e, "SDSS Catalog Query Failed - network Error");
    } catch (Exception e) {
        _log.error(e, e.toString());
        throw makeException(e, "SDSS Catalog Query Failed");
    }
    return outFile;
}

From source file:net.hockeyapp.android.tasks.CheckUpdateTask.java

protected URLConnection createConnection(URL url) throws IOException {
    URLConnection connection = url.openConnection();
    connection.addRequestProperty("User-Agent", "HockeySDK/Android");
    // connection bug workaround for SDK<=2.x
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD) {
        connection.setRequestProperty("connection", "close");
    }//from w  w w  .ja va 2  s . c  o m
    return connection;
}

From source file:com.bt.heliniumstudentapp.UpdateClass.java

@Override
protected String doInBackground(Void... Void) {
    try {//from   w w w .  j a va 2 s .  co m
        URLConnection connection = new URL(HeliniumStudentApp.URL_UPDATE_CHANGELOG).openConnection();

        connection.setConnectTimeout(HeliniumStudentApp.TIMEOUT_CONNECT);
        connection.setReadTimeout(HeliniumStudentApp.TIMEOUT_READ);

        connection.setRequestProperty("Accept-Charset", HeliniumStudentApp.CHARSET);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded;charset=" + HeliniumStudentApp.CHARSET);

        connection.connect();

        final Scanner line = new Scanner(connection.getInputStream()).useDelimiter("\\A");
        final String html = line.hasNext() ? line.next() : "";

        ((HttpURLConnection) connection).disconnect();

        if (((HttpURLConnection) connection).getResponseCode() == 200)
            return html;
        else
            return null;
    } catch (IOException e) {
        return null;
    }
}