Example usage for java.net HttpURLConnection getResponseMessage

List of usage examples for java.net HttpURLConnection getResponseMessage

Introduction

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

Prototype

public String getResponseMessage() throws IOException 

Source Link

Document

Gets the HTTP response message, if any, returned along with the response code from a server.

Usage

From source file:edwardawebb.queueman.classes.NetFlix.java

public NetFlixQueue getSearchResults(String searchTerm) {
    searchQueue = new NetFlixQueue(NetFlixQueue.QUEUE_TYPE_SEARCH);
    setSignPost(user.getAccessToken(), user.getAccessTokenSecret());

    InputStream xml = null;//ww w .  j a va 2  s. com
    try {
        String encSearchTerm = URLEncoder.encode(searchTerm);
        setSignPost(user.getAccessToken(), user.getAccessTokenSecret());
        String expanders = "&expand=synopsis,formats";
        URL QueueUrl = null;

        QueueUrl = new URL("http://api.netflix.com/catalog/titles?term=" + encSearchTerm + expanders);
        // Log.d("NetFlix",""+QueueUrl.toString())
        HttpURLConnection request = (HttpURLConnection) QueueUrl.openConnection();

        NetFlix.oaconsumer.sign(request);
        request.connect();

        lastResponseMessage = request.getResponseCode() + ": " + request.getResponseMessage();

        if (request.getResponseCode() == 200) {
            // Log.d("NetFlix", request.getContentType())
            // //Log.d("NetFlix",request.getInputStream().toString())
            // return xml xmldoc
            xml = request.getInputStream();

            /*BufferedReader in = new BufferedReader(new InputStreamReader(
                  xml));
            String linein = null;
            while ((linein = in.readLine()) != null) {
               Log.d("NetFlix", "SearchMovie: " + linein);
            }*/
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp;

            sp = spf.newSAXParser();

            XMLReader xr = sp.getXMLReader();
            // SearchResultsHandler myHandler = new
            // SearchResultsHandler(this);
            SearchQueueHandler myHandler = new SearchQueueHandler();
            xr.setContentHandler(myHandler);
            xr.parse(new InputSource(xml));
        }

    } catch (ParserConfigurationException e) {

        reportError(e, lastResponseMessage);
    } catch (SAXException e) {

        reportError(e, lastResponseMessage);
    } catch (IOException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "IO Error connecting to NetFlix queue")
    } catch (OAuthMessageSignerException e) {

        reportError(e, lastResponseMessage);
    } catch (OAuthExpectationFailedException e) {

        reportError(e, lastResponseMessage);
    }

    return searchQueue;
}

From source file:edwardawebb.queueman.classes.NetFlix.java

public boolean getNewETag(int queueType, int discPosition) {
    URL QueueUrl = null;//ww  w. j  a  v a2  s  .  c o m
    DefaultHandler myQueueHandler = null;
    boolean result = false;
    //start index is 0 based, so step the true position down one
    String expanders = "?max_results=" + 1 + "&start_index=" + (discPosition - 1);
    InputStream xml = null;
    try {
        switch (queueType) {
        case NetFlixQueue.QUEUE_TYPE_INSTANT:
            QueueUrl = new URL(
                    "http://api.netflix.com/users/" + user.getUserId() + "/queues/instant" + expanders);
            myQueueHandler = new InstantETagHandler();
            break;
        case NetFlixQueue.QUEUE_TYPE_DISC:
            QueueUrl = new URL(
                    "http://api.netflix.com/users/" + user.getUserId() + "/queues/disc/available" + expanders);

            myQueueHandler = new DiscETagHandler();
            break;
        }
        setSignPost(user.getAccessToken(), user.getAccessTokenSecret());
        HttpURLConnection request = (HttpURLConnection) QueueUrl.openConnection();

        NetFlix.oaconsumer.sign(request);
        request.connect();

        lastResponseMessage = request.getResponseCode() + ": " + request.getResponseMessage();

        if (request.getResponseCode() == 200) {
            xml = request.getInputStream();

            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp;
            sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();

            xr.setContentHandler(myQueueHandler);
            //our custom handler will throw an exception when he gets what he want, interupting the full parse
            ErrorProcessor errors = new ErrorProcessor();
            xr.setErrorHandler(errors);
            xr.parse(new InputSource(xml));
            result = true;
        }

    } catch (ParserConfigurationException e) {

        reportError(e, lastResponseMessage);
    } catch (SAXException e) {

        reportError(e, lastResponseMessage);
    } catch (IOException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "IO Error connecting to NetFlix queue")
    } catch (OAuthMessageSignerException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "Unable to Sign request - token invalid")
    } catch (OAuthExpectationFailedException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "Expectation failed")
    }
    return result;
}

From source file:com.androidex.volley.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws AuthFailureError, IOException {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());// w  w  w  . j a v  a 2 s  . com
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);

    if (!TextUtils.isEmpty(mUserAgent)) {
        connection.setRequestProperty(HEADER_USER_AGENT, mUserAgent);
    }

    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    if (request instanceof MultiPartRequest) {
        setConnectionParametersForMultipartRequest(connection, request);
    } else {
        setConnectionParametersForRequest(connection, request);
    }

    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could
        // not be retrieved.
        // Signal to the caller that something was wrong with the
        // connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

From source file:edwardawebb.queueman.classes.NetFlix.java

/**
 * //from w  w  w  . j  a  v  a2s.c om
 * @param queueType
 * @param maxResults
 * @return HttpStatusCOde or NF_ERROR_BAD_DEFAULT for exceptions
 */
public int getRecommendations(int startIndex, String maxResults) {
    times[0] = System.currentTimeMillis();
    URL QueueUrl = null;
    int result = NF_ERROR_BAD_DEFAULT;
    if (maxResults.equals(QueueMan.ALL_TITLES_STRING)) {
        maxResults = "500";
    }

    String expanders = "?expand=synopsis,formats&start_index=" + startIndex + "&max_results=" + maxResults;
    InputStream xml = null;
    try {
        // we're either rotating/task jumping OR we're starting/paging
        /*if (!NetFlix.recomemendedQueue.isEmpty() && startIndex == recomemendedQueue.getStartIndex()){
           return 200;
        }else if(recomemendedQueue.getTotalTitles() < startIndex){
           return NF_ERROR_NO_MORE;
        }else{
           recomemendedQueue.purge();
        }*/

        QueueUrl = new URL("http://api.netflix.com/users/" + user.getUserId() + "/recommendations" + expanders);
        RecommendationsHandler myHandler = new RecommendationsHandler(this);
        Log.d("NetFlix", "" + QueueUrl.toString());

        setSignPost(user.getAccessToken(), user.getAccessTokenSecret());
        HttpURLConnection request = (HttpURLConnection) QueueUrl.openConnection();

        NetFlix.oaconsumer.sign(request);
        request.connect();

        lastResponseMessage = request.getResponseCode() + ": " + request.getResponseMessage();
        result = request.getResponseCode();
        xml = request.getInputStream();

        /*   BufferedReader in = new BufferedReader(new
               InputStreamReader(xml)); String linein = null; while ((linein =
               in.readLine()) != null) { Log.d("NetFlixQueue", "" +
               linein); }*/

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp;
        sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        xr.setContentHandler(myHandler);
        xr.parse(new InputSource(xml));

    } catch (ParserConfigurationException e) {

        reportError(e, lastResponseMessage);
    } catch (SAXException e) {

        reportError(e, lastResponseMessage);
    } catch (IOException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "IO Error connecting to NetFlix queue")
    } catch (OAuthMessageSignerException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "Unable to Sign request - token invalid")
    } catch (OAuthExpectationFailedException e) {

        reportError(e, lastResponseMessage);
        // Log.i("NetFlix", "Expectation failed")
    }
    times[1] = System.currentTimeMillis();
    return result;
}

From source file:dbf.parser.pkg2.handler.java

private void sendPost(String json) throws Exception {
    System.out.println("Adding url ..");
    String url = "http://shorewindowcleaning:withwindows@ironside.ddns.net:5984/shorewindowcleaning/_bulk_docs";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    //con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept", "application/json");
    con.setRequestProperty("Content-Type", "application/json");
    String basicAuth = "Basic " + new String(new Base64().encode(obj.getUserInfo().getBytes()));
    con.setRequestProperty("Authorization", basicAuth);

    //String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
    System.out.println("Adding output ..");
    // Send post request
    con.setDoOutput(true);/*from  w  w  w  .  ja v  a  2 s .  com*/
    OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
    wr.write(json);
    wr.flush();
    wr.close();
    System.out.println("geting content ..");
    // System.out.println(con.getResponseMessage());
    int responseCode = con.getResponseCode();
    System.out.println("Adding checking response ..");
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + json);
    System.out.println("Response Code : " + responseCode);
    System.out.println(con.getResponseMessage());
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());

}

From source file:com.daidiansha.acarry.control.network.core.volley.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws AuthFailureError, IOException {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//from  w  w w  . ja  v a  2  s. co m
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);

    if (!TextUtils.isEmpty(mUserAgent)) {
        connection.setRequestProperty(HEADER_USER_AGENT, mUserAgent);
    }

    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    if (request instanceof MultiPartRequest) {
        setConnectionParametersForMultipartRequest(connection, (MultiPartRequest) request);
    } else {
        setConnectionParametersForRequest(connection, request);
    }

    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could
        // not be retrieved.
        // Signal to the caller that something was wrong with the
        // connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

From source file:com.volley.air.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws AuthFailureError, IOException {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<>();
    map.putAll(request.getHeaders());/* w w w. j  a  va  2 s.c  om*/
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);

    if (!TextUtils.isEmpty(mUserAgent)) {
        connection.setRequestProperty(HEADER_USER_AGENT, mUserAgent);
    }

    for (Entry<String, String> entry : map.entrySet()) {
        connection.addRequestProperty(entry.getKey(), entry.getValue());
    }
    if (request instanceof MultiPartRequest) {
        setConnectionParametersForMultipartRequest(connection, request);
    } else {
        setConnectionParametersForRequest(connection, request);
    }

    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could
        // not be retrieved.
        // Signal to the caller that something was wrong with the
        // connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

From source file:com.juick.android.Utils.java

public static RESTResponse postForm(final Context context, final String url, ArrayList<NameValuePair> data) {
    try {/*  ww  w.ja v  a2  s  . c  o  m*/
        final String end = "\r\n";
        final String twoHyphens = "--";
        final String boundary = "****+++++******+++++++********";

        URL apiUrl = new URL(url);

        final HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection();
        conn.setConnectTimeout(10000);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.connect();
        OutputStream out = conn.getOutputStream();

        PrintStream ps = new PrintStream(out);
        int index = 0;
        byte[] block = new byte[1024];
        for (NameValuePair nameValuePair : data) {
            ps.print(twoHyphens + boundary + end);
            ps.print("Content-Disposition: form-data; name=\"" + nameValuePair.getName() + "\"" + end + end);
            final InputStream value = nameValuePair.getValue();
            while (true) {
                final int rd = value.read(block, 0, block.length);
                if (rd < 1) {
                    break;
                }
                ps.write(block, 0, rd);
            }
            value.close();
            ps.print(end);
        }
        ps.print(twoHyphens + boundary + twoHyphens + end);
        ps.close();
        boolean b = conn.getResponseCode() == 200;
        if (!b) {
            return new RESTResponse("HTTP " + conn.getResponseCode() + ": " + conn.getResponseMessage(), false,
                    null);
        } else {
            InputStream inputStream = conn.getInputStream();
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] arr = new byte[1024];
                while (true) {
                    int rd = inputStream.read(arr);
                    if (rd < 1)
                        break;
                    baos.write(arr, 0, rd);
                }
                if (conn.getHeaderField("X-GZIPCompress") != null) {
                    return new RESTResponse(null, false, baos.toString(0));
                } else {
                    return new RESTResponse(null, false, baos.toString());
                }
            } finally {
                inputStream.close();
            }
        }
    } catch (IOException e) {
        return new RESTResponse(e.toString(), false, null);
    }
}

From source file:com.github.gcauchis.scalablepress4j.api.AbstractRestApi.java

/**
 * Call request for entity.//from   w w  w .j  a  v  a  2s  . c  o m
 *
 * @param <T> the generic type
 * @param url the url
 * @param requestMethod the http request method
 * @param request the request
 * @param responseType the response type
 * @param urlVariables the url variables
 * @return the response
 */
private <T> Response<T> forEntity(String url, String requestMethod, Object request, Class<T> responseType,
        Map<String, ?> urlVariables) {
    StringBuilder response = new StringBuilder();
    HttpURLConnection connection = prepareConnection(url, requestMethod, urlVariables);
    try {

        // // Send request
        DataOutputStream wr = null;
        if (request != null) {
            String content = objectMapper.writeValueAsString(request);
            wr = new DataOutputStream(connection.getOutputStream());
            wr.write(content.getBytes(StandardCharsets.UTF_8));
            wr.flush();
        }

        // Get Response
        BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\n');
        }

        if (wr != null) {
            wr.close();
        }
        rd.close();
        log.trace("Response {}", response);
    } catch (IOException e) {
        log.error("Fail to send request", e);
        ErrorResponse errorResponse = new ErrorResponse();
        try {
            errorResponse.setStatusCode(connection.getResponseCode() + "");
            errorResponse.setMessage(connection.getResponseMessage());
        } catch (IOException e1) {
            errorResponse.setStatusCode("500");
            errorResponse.setMessage(e.getMessage());
        }
        throw new ScalablePressBadRequestException(errorResponse);
    }

    Response<T> responseEntity = new Response<>();
    responseEntity.headers = connection.getHeaderFields();
    log.debug("Header: {}", responseEntity.headers);
    try {
        responseEntity.body = objectMapper.readValue(response.toString(), responseType);
    } catch (IOException e) {
        log.error("Fail to parse response", e);
        ErrorResponse errorResponse = null;
        try {
            log.error("Response error: {} {}", connection.getResponseCode(), connection.getResponseMessage());
            errorResponse = objectMapper.readValue(response.toString(), ErrorResponse.class);
        } catch (IOException ioe) {
            log.error("Fail to parse error", ioe);
        }
        if (errorResponse != null) {
            log.error("Response error object: {}", errorResponse);
            throw new ScalablePressBadRequestException(errorResponse);
        }
    }
    return responseEntity;
}

From source file:net.namecoin.NameCoinI2PResolver.HttpSession.java

public String executePost(String postdata) throws HttpSessionException {
    URL url;// ww  w.  ja v a2 s .  c  o m
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(this.uri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", POST_CONTENT_TYPE);
        connection.setRequestProperty("User-Agent", "java");

        if (!this.user.isEmpty() && !this.password.isEmpty()) {
            String authString = this.user + ":" + this.password;
            String authStringEnc = Base64.encodeBytes(authString.getBytes());
            connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        }

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(postdata);
        wr.flush();
        wr.close();

        //Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }

        rd.close();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new HttpSessionException("Server returned: " + connection.getResponseMessage());
        }

        return response.toString();

    } catch (Exception e) {
        throw new HttpSessionException(e.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}