Example usage for java.net HttpURLConnection getErrorStream

List of usage examples for java.net HttpURLConnection getErrorStream

Introduction

In this page you can find the example usage for java.net HttpURLConnection getErrorStream.

Prototype

public InputStream getErrorStream() 

Source Link

Document

Returns the error stream if the connection failed but the server sent useful data nonetheless.

Usage

From source file:com.mycompany.grupo6ti.GenericResource.java

@POST
@Produces("application/json")
@Path("/rechazarFactura/{id}/{motivo}")
public String rechazarFactura(@PathParam("id") String id, @PathParam("motivo") String motivo) {
    try {/*from   w  w  w.jav a 2 s . co m*/
        URL url = new URL("http://localhost:85/reject/");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        InputStream is;
        conn.setRequestProperty("Accept-Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setUseCaches(true);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);

        String idJson = "{\n" + "  \"id\": \"" + id + "\",\n" + "  \"motivo\": \"" + motivo + "\"\n" + "}";
        //String idJson2 = "[\"Test\", \"Funcionando Bien\"]";
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write(idJson);
        out.flush();
        out.close();

        if (conn.getResponseCode() >= 400) {
            is = conn.getErrorStream();
        } else {
            is = conn.getInputStream();
        }
        String result2 = "";
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = rd.readLine()) != null) {
            result2 += line;
        }
        rd.close();
        return result2;

    } catch (IOException e) {
        e.printStackTrace();
        return ("[\"Test\", \"Funcionando Bien1\"]");
    } catch (Exception e) {
        e.printStackTrace();
        return ("[\"Test\", \"Funcionando Bien2\"]");
    }

    //return ("[\"Test\", \"Funcionando Bien\"]");

}

From source file:com.ipservices.alarmcallback.victorops.VictorOpsClient.java

public void sendAlert(Stream stream, final AlertCondition.CheckResult checkResult, final String entityId)
        throws AlarmCallbackException {
    final HttpURLConnection conn;

    try {/*from   w w  w .j  av a  2s . c om*/
        if (proxyUri != null) {
            final InetSocketAddress proxyAddress = new InetSocketAddress(proxyUri.getHost(),
                    proxyUri.getPort());
            final Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
            conn = (HttpURLConnection) apiUrl.openConnection(proxy);
        } else {
            conn = (HttpURLConnection) apiUrl.openConnection();
        }
        conn.setRequestMethod("POST");
    } catch (IOException e) {
        throw new AlarmCallbackException("Error while opening connection to VictorOps API.", e);
    }

    conn.setDoOutput(true);
    try (final OutputStream requestStream = conn.getOutputStream()) {
        final VictorOpsAlert alert = new VictorOpsAlert(messageType, baseUrl);
        alert.build(stream, checkResult, entityId);

        requestStream.write(objectMapper.writeValueAsBytes(alert));
        requestStream.flush();

        final InputStream responseStream;
        if (conn.getResponseCode() == 200) {
            responseStream = conn.getInputStream();
        } else {
            LOG.warn("Received response {} from server.", conn.getResponseCode());
            responseStream = conn.getErrorStream();
        }

        final VictorOpsAlertReply reply = objectMapper.readValue(responseStream, VictorOpsAlertReply.class);
        if ("success".equals(reply.result)) {
            LOG.debug("Successfully sent alert to VictorOps with entity id {}", reply.entityId);
        } else {
            LOG.warn("Error while creating VictorOps alert: {}", reply.message);
            throw new AlarmCallbackException("Error while creating VictorOps event: " + reply.message);
        }
    } catch (IOException e) {
        throw new AlarmCallbackException("Could not POST alert notification to VictorOps API.", e);
    }
}

From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java

/**
 * Apply normalization rules to the identifier supplied by the End-User 
 * to determine the Resource and Host. Then make an HTTP GET request to
 * the host's WebFinger endpoint to obtain the location of the requested 
 * service/*from w  w w.j  a  v a2  s . c o m*/
 * return the issuer location ("href")
 * @param user_input , domain
 * @return
 */

public static String webfinger(String userInput, String serverUrl) {
    // android.os.Debug.waitForDebugger();

    String result = ""; // result of the http request (a json object
    // converted to string)
    String postUrl = "";
    String host = null;
    String href = null;

    // URI identifying the type of service whose location is being requested
    final String rel = "http://openid.net/specs/connect/1.0/issuer";

    if (!isEmpty(userInput)) {

        try {
            // normalizes this URI's path
            URI uri = new URI(userInput).normalize();
            String[] parts = uri.getRawSchemeSpecificPart().split("@");

            if (!isEmpty(serverUrl)) {
                // use serverUrl if specified
                if (serverUrl.startsWith("https://")) {
                    host = serverUrl.substring(8);
                } else if (serverUrl.startsWith("http://")) {
                    host = serverUrl.substring(7);
                } else {
                    host = serverUrl;
                }
            } else if (parts.length > 1) {
                // the user is using an E-Mail Address Syntax
                host = parts[parts.length - 1];
            } else {
                // the user is using an other syntax
                host = uri.getHost();
            }

            // check if host is valid
            if (host == null) {
                return null;
            }

            if (!host.endsWith("/"))
                host += "/";
            postUrl = "https://" + host + ".well-known/webfinger?resource=" + userInput + "&rel=" + rel;

            // log the request
            Logd(TAG, "Web finger request\n GET " + postUrl + "\n HTTP /1.1" + "\n Host: " + host);
            // Send an HTTP get request with the resource and rel parameters
            HttpURLConnection huc = getHUC(postUrl);
            huc.setDoOutput(true);
            huc.setRequestProperty("Content-Type", "application/jrd+json");
            huc.connect();

            try {

                int responseCode = huc.getResponseCode();
                Logd(TAG, "webfinger responseCode: " + responseCode);
                // if 200, read http body
                if (responseCode == 200) {
                    InputStream is = huc.getInputStream();
                    result = convertStreamToString(is);
                    is.close();
                    Logd(TAG, "webfinger result: " + result);

                    // The response is a json object and the issuer location
                    // is returned as the value of the href member
                    // a links array element with the rel member value
                    // http://openid.net/specs/connect/1.0/issuer
                    JSONObject jo = new JSONObject(result);
                    JSONObject links = jo.getJSONArray("links").getJSONObject(0);
                    href = links.getString("href");
                    Logd(TAG, "webfinger reponse href: " + href);

                } else {
                    // why the request didn't succeed
                    href = huc.getResponseMessage();
                }

                // close connection
                huc.disconnect();
            } catch (IOException ioe) {
                Logd(TAG, "webfinger io exception: " + huc.getErrorStream());
                ioe.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        // the user_input is empty
        href = "no identifier detected!!\n";
    }
    return href;
}

From source file:com.github.mhendred.face4j.ResponderImpl.java

/** 
 * @see {@link Responder#doPost(URI, List)}
 *//*w  w  w .  ja va 2 s. co m*/
public String doPost(final URI uri, final List<NameValuePair> params)
        throws FaceClientException, FaceServerException {
    try {
        URL url = uri.toURL();

        StringBuilder strparams = new StringBuilder();
        for (Iterator iterator = params.iterator(); iterator.hasNext();) {
            NameValuePair nameValuePair = (NameValuePair) iterator.next();
            strparams.append(nameValuePair.getName());
            strparams.append("=");
            strparams.append(nameValuePair.getValue());
            strparams.append("&");
        }

        strparams.deleteCharAt(strparams.length() - 1);
        byte[] postData = strparams.toString().getBytes();
        String urlpath = url.toString();
        url = new URL(urlpath + "?" + strparams.toString());

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        /*connection.setRequestProperty("X-Custom-Header", "xxx");
        connection.setRequestProperty("Content-Type", "application/json");*/

        // POST the http body data
        //          connection.setDoOutput(true);
        //connection.setRequestMethod("GET");

        /*connection.setRequestProperty( "Content-Length",Integer.toString( postData.length ));
        DataOutputStream  writer = new DataOutputStream(connection.getOutputStream());
        writer.write(postData);
        writer.close();*/

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // OK
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer res = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                res.append(line);
            }
            reader.close();

            return res.toString();

        } else {
            int resp = connection.getResponseCode();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            StringBuffer res = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                res.append(line);
            }
            reader.close();
            return line;
        }

    }

    catch (IOException ioe) {
        throw new FaceClientException(ioe);
    }
}

From source file:com.geozen.demo.foursquare.jiramot.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*from   w w w.ja va2 s.c  o  m*/
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url
 *            - the resource to open: must be a welformed URL
 * @param method
 *            - the HTTP method to use ("GET", "POST", etc.)
 * @param params
 *            - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException
 *             - if the URL format is invalid
 * @throws IOException
 *             - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Foursquare-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " GeoZen");

    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:net.sbbi.upnp.messages.StateVariableMessage.java

/**
 * Executes the state variable query and retuns the UPNP device response, according to the UPNP specs,
 * this method could take up to 30 secs to process ( time allowed for a device to respond to a request )
 * @return a state variable response object containing the variable value
 * @throws IOException if some IOException occurs during message send and reception process
 * @throws UPNPResponseException if an UPNP error message is returned from the server
 *         or if some parsing exception occurs ( detailErrorCode = 899, detailErrorDescription = SAXException message )
 *///from   w  ww  .j  a  v  a2s  .c o  m
public StateVariableResponse service() throws IOException, UPNPResponseException {
    StateVariableResponse rtrVal = null;
    UPNPResponseException upnpEx = null;
    IOException ioEx = null;
    StringBuffer body = new StringBuffer(256);

    body.append("<?xml version=\"1.0\"?>\r\n");
    body.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"");
    body.append(" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
    body.append("<s:Body>");
    body.append("<u:QueryStateVariable xmlns:u=\"urn:schemas-upnp-org:control-1-0\">");
    body.append("<u:varName>").append(serviceStateVar.getName()).append("</u:varName>");
    body.append("</u:QueryStateVariable>");
    body.append("</s:Body>");
    body.append("</s:Envelope>");

    if (log.isDebugEnabled())
        log.debug("POST prepared for URL " + service.getControlURL());
    URL url = new URL(service.getControlURL().toString());
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    HttpURLConnection.setFollowRedirects(false);
    //conn.setConnectTimeout( 30000 );
    conn.setRequestProperty("HOST", url.getHost() + ":" + url.getPort());
    conn.setRequestProperty("SOAPACTION", "\"urn:schemas-upnp-org:control-1-0#QueryStateVariable\"");
    conn.setRequestProperty("CONTENT-TYPE", "text/xml; charset=\"utf-8\"");
    conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length()));
    OutputStream out = conn.getOutputStream();
    out.write(body.toString().getBytes());
    out.flush();
    conn.connect();
    InputStream input = null;

    if (log.isDebugEnabled())
        log.debug("executing query :\n" + body);
    try {
        input = conn.getInputStream();
    } catch (IOException ex) {
        // java can throw an exception if he error code is 500 or 404 or something else than 200
        // but the device sends 500 error message with content that is required
        // this content is accessible with the getErrorStream
        input = conn.getErrorStream();
    }

    if (input != null) {
        int response = conn.getResponseCode();
        String responseBody = getResponseBody(input);
        if (log.isDebugEnabled())
            log.debug("received response :\n" + responseBody);
        SAXParserFactory saxParFact = SAXParserFactory.newInstance();
        saxParFact.setValidating(false);
        saxParFact.setNamespaceAware(true);
        StateVariableResponseParser msgParser = new StateVariableResponseParser(serviceStateVar);
        StringReader stringReader = new StringReader(responseBody);
        InputSource src = new InputSource(stringReader);
        try {
            SAXParser parser = saxParFact.newSAXParser();
            parser.parse(src, msgParser);
        } catch (ParserConfigurationException confEx) {
            // should never happen
            // we throw a runtimeException to notify the env problem
            throw new RuntimeException(
                    "ParserConfigurationException during SAX parser creation, please check your env settings:"
                            + confEx.getMessage());
        } catch (SAXException saxEx) {
            // kind of tricky but better than nothing..
            upnpEx = new UPNPResponseException(899, saxEx.getMessage());
        } finally {
            try {
                input.close();
            } catch (IOException ex) {
                // ignoring
            }
        }
        if (upnpEx == null) {
            if (response == HttpURLConnection.HTTP_OK) {
                rtrVal = msgParser.getStateVariableResponse();
            } else if (response == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                upnpEx = msgParser.getUPNPResponseException();
            } else {
                ioEx = new IOException("Unexpected server HTTP response:" + response);
            }
        }
    }
    try {
        out.close();
    } catch (IOException ex) {
        // ignore
    }
    conn.disconnect();
    if (upnpEx != null) {
        throw upnpEx;
    }
    if (rtrVal == null && ioEx == null) {
        ioEx = new IOException("Unable to receive a response from the UPNP device");
    }
    if (ioEx != null) {
        throw ioEx;
    }
    return rtrVal;
}

From source file:com.jiramot.foursquare.android.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 *
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 *
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String//w w w.  j  a va 2  s.co  m
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Foursquare-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FoursquareAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:br.com.ufc.palestrasufc.twitter.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * // w w w  .  j a va2s .c o  m
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Twitter-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " TwitterAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:com.example.socketmobile.android.warrantychecker.network.UserRegistration.java

private Object fetchWarranty(String id, String authString, String query) throws IOException {
    InputStream is = null;//from w w  w.  j av a 2  s.com
    RegistrationApiResponse result = null;
    RegistrationApiErrorResponse errorResult = null;
    String authHeader = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

    try {
        URL url = new URL(baseUrl + id + "/registrations");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(10000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(query);
        writer.flush();
        writer.close();
        os.close();

        conn.connect();
        int response = conn.getResponseCode();

        Log.d(TAG, "Warranty query responded: " + response);
        switch (response / 100) {
        case 2:
            is = conn.getInputStream();
            RegistrationApiResponse.Reader reader = new RegistrationApiResponse.Reader();
            result = reader.readJsonStream(is);
            break;
        case 4:
        case 5:
            is = conn.getErrorStream();

            RegistrationApiErrorResponse.Reader errorReader = new RegistrationApiErrorResponse.Reader();
            errorResult = errorReader.readErrorJsonStream(is);

            break;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        if (is != null) {
            is.close();
        }
    }
    return (result != null) ? result : errorResult;
}

From source file:com.qburst.android.linkedin.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*from ww  w . ja v a 2  s  .co m*/
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Twitter-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " LinkedInAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}