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:bluevia.SendSMS.java

public static void setFacebookWallPost(String userEmail, String post) {
    try {/*from ww  w . ja v  a2s  .  c o  m*/

        Properties facebookAccount = Util.getNetworkAccount(userEmail, Util.FaceBookOAuth.networkID);

        if (facebookAccount != null) {
            String access_key = facebookAccount.getProperty(Util.FaceBookOAuth.networkID + ".access_key");

            com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate();

            Entity blueviaUser = Util.getUser(userEmail);

            //FIXME
            URL fbAPI = new URL(
                    "https://graph.facebook.com/" + (String) blueviaUser.getProperty("alias") + "/feed");
            HttpURLConnection request = (HttpURLConnection) fbAPI.openConnection();

            String content = String.format("access_token=%s&message=%s", access_key,
                    URLEncoder.encode(post, "UTF-8"));

            request.setRequestMethod("POST");
            request.setRequestProperty("Content-Type", "javascript/text");
            request.setRequestProperty("Content-Length", "" + Integer.toString(content.getBytes().length));
            request.setDoOutput(true);
            request.setDoInput(true);

            OutputStream os = request.getOutputStream();
            os.write(content.getBytes());
            os.flush();
            os.close();

            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            int rc = request.getResponseCode();
            if (rc == HttpURLConnection.HTTP_OK) {
                StringBuffer body = new StringBuffer();
                String line;

                do {
                    line = br.readLine();
                    if (line != null)
                        body.append(line);
                } while (line != null);

                JSONObject id = new JSONObject(body.toString());
            } else
                log.severe(
                        String.format("Error %d posting FaceBook wall:%s\n", rc, request.getResponseMessage()));
        }
    } catch (Exception e) {
        log.severe(String.format("Exception posting FaceBook wall: %s", e.getMessage()));
    }
}

From source file:export.Facebook.java

private JSONObject createRun(JSONObject ref, JSONObject runObj) throws Exception {
    int sport = runObj.optInt("sport", DB.ACTIVITY.SPORT_OTHER);
    if (sport != DB.ACTIVITY.SPORT_RUNNING && sport != DB.ACTIVITY.SPORT_BIKING) {

        /* only running and biking is supported */
        return null;
    }/*  ww w.  j a  va2 s . c  o  m*/
    String id = ref.getString("id");
    ArrayList<Part<?>> list = new ArrayList<Part<?>>();
    list.add(new Part<StringWritable>("access_token", new StringWritable(FormCrawler.URLEncode(access_token))));
    list.add(new Part<StringWritable>("course", new StringWritable(id)));
    if (explicitly_shared)
        list.add(new Part<StringWritable>("fb:explicitly_shared", new StringWritable("true")));

    list.add(new Part<StringWritable>("start_time",
            new StringWritable(formatTime(runObj.getLong("startTime")))));
    if (runObj.has("endTime")) {
        list.add(new Part<StringWritable>("end_time",
                new StringWritable(formatTime(runObj.getLong("endTime")))));
    }

    if (uploadComment && runObj.has("comment")) {
        list.add(new Part<StringWritable>("message", new StringWritable(runObj.getString("comment"))));
    }

    Part<?> parts[] = new Part<?>[list.size()];
    list.toArray(parts);

    URL url = new URL(sport == DB.ACTIVITY.SPORT_RUNNING ? RUN_ENDPOINT : BIKE_ENDPOINT);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    postMulti(conn, parts);

    int code = conn.getResponseCode();
    String msg = conn.getResponseMessage();

    InputStream in = new BufferedInputStream(conn.getInputStream());
    JSONObject runRef = parse(in);

    conn.disconnect();
    if (code != 200) {
        throw new Exception("Got code: " + code + ", msg: " + msg + " from " + url.toString());
    }

    return runRef;
}

From source file:net.solarnetwork.node.support.HttpClientSupport.java

/**
 * HTTP POST data as {@code application/x-www-form-urlencoded} (e.g. a web
 * form) to a URL.//from w  w w .  j  a v  a  2  s .c  o m
 * 
 * @param url
 *        the URL to post to
 * @param accept
 *        the value to use for the Accept HTTP header
 * @param data
 *        the data to encode and send as the body of the HTTP POST
 * @return the URLConnection after the post data has been sent
 * @throws IOException
 *         if any IO error occurs
 * @throws RuntimeException
 *         if the HTTP response code is not within the 200 - 299 range
 */
protected URLConnection postXWWWFormURLEncodedData(String url, String accept, Map<String, ?> data)
        throws IOException {
    URLConnection conn = getURLConnection(url, HTTP_METHOD_POST, accept);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    String body = xWWWFormURLEncoded(data);
    log.trace("Encoded HTTP POST data {} as {}", data, body);
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
    FileCopyUtils.copy(new StringReader(body), out);
    if (conn instanceof HttpURLConnection) {
        HttpURLConnection http = (HttpURLConnection) conn;
        int status = http.getResponseCode();
        if (status < 200 || status > 299) {
            throw new RuntimeException("HTTP result status not in the 200-299 range: " + http.getResponseCode()
                    + " " + http.getResponseMessage());
        }
    }
    return conn;
}

From source file:export.Facebook.java

private JSONObject createCourse(JSONObject course) throws JSONException, IOException, Exception {
    JSONObject obj = new JSONObject();
    /* create a facebook course instance */
    obj.put("fb:app_id", Facebook.CLIENT_ID);
    obj.put("og:type", "fitness.course");
    obj.put("og:title", "a RunnerUp course");
    obj.put("fitness", course);

    Part<StringWritable> themePart = new Part<StringWritable>("access_token",
            new StringWritable(FormCrawler.URLEncode(access_token)));
    Part<StringWritable> payloadPart = new Part<StringWritable>("object", new StringWritable(obj.toString()));
    Part<?> parts[] = { themePart, payloadPart };

    HttpURLConnection conn = (HttpURLConnection) new URL(COURSE_ENDPOINT).openConnection();
    conn.setDoOutput(true);/* w w w.  j a  va2  s  .com*/
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    postMulti(conn, parts);

    int code = conn.getResponseCode();
    String msg = conn.getResponseMessage();

    InputStream in = new BufferedInputStream(conn.getInputStream());
    JSONObject ref = parse(in);

    conn.disconnect();
    if (code != 200) {
        throw new Exception("got " + code + ": >" + msg + "< from createCourse");
    }

    return ref;
}

From source file:net.sf.okapi.filters.drupal.DrupalConnector.java

public boolean updateNode(Node node) {
    try {/*  w  ww  . j  a  v a 2s. c  o  m*/
        URL url = new URL(host + String.format("rest/node/" + node.getNid()));
        HttpURLConnection conn = createConnection(url, "PUT", true);

        OutputStream os = conn.getOutputStream();
        os.write(node.toString().getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            System.out.println(conn.getResponseCode());
            System.out.println(conn.getResponseMessage());
            throw new RuntimeException("Operation failed: " + conn.getResponseCode());
        }

        conn.disconnect();
        return true;
    } catch (Throwable e) {
        throw new RuntimeException("Error in updateNode(): " + e.getMessage(), e);
    }
}

From source file:org.runnerup.export.FacebookSynchronizer.java

private JSONObject createObj(URL url, Part<?> parts[]) throws Exception {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);//ww w . j  a v  a  2s. co  m
    conn.setDoInput(true);
    conn.setRequestMethod(RequestMethod.POST.name());
    SyncHelper.postMulti(conn, parts);

    int code = conn.getResponseCode();
    String msg = conn.getResponseMessage();

    if (code != HttpStatus.SC_OK) {
        conn.disconnect();
        throw new Exception("Got code: " + code + ", msg: " + msg + " from " + url.toString());
    } else {
        InputStream in = new BufferedInputStream(conn.getInputStream());
        JSONObject runRef = SyncHelper.parse(in);

        conn.disconnect();
        return runRef;
    }
}

From source file:net.sf.okapi.filters.drupal.DrupalConnector.java

public boolean postNode(Node node) {
    try {//from   w ww . j  ava 2  s  . co m
        URL url = new URL(host + String.format("rest/node"));
        HttpURLConnection conn = createConnection(url, "POST", true);

        OutputStream os = conn.getOutputStream();
        os.write(node.toString().getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            System.out.println(conn.getResponseCode());
            System.out.println(conn.getResponseMessage());
            throw new RuntimeException("Operation failed: " + conn.getResponseCode());
        }

        conn.disconnect();
        return true;
    } catch (Throwable e) {
        throw new RuntimeException("Error in postNode(): " + e.getMessage(), e);
    }
}

From source file:com.francetelecom.clara.cloud.paas.it.services.helper.PaasServicesEnvApplicationAccessHelper.java

/**
 * Check if a string appear in the html page
 *
 * @param url//from ww  w  . ja v a 2s .  c  o  m
 *            URL to test
 * @param token
 *            String that must be in html page
 * @return Cookie that identifies the was or null if the test failed. An
 *         empty string means that no cookie was found in the request, but
 *         the check succeeded.
 */
private static String checkStringAndReturnCookie(URL url, String token, String httpProxyHost,
        int httpProxyPort) {
    InputStream is = null;
    String cookie = null;
    try {
        HttpURLConnection connection;
        if (httpProxyHost != null) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort));
            connection = (HttpURLConnection) url.openConnection(proxy);
        } else {
            connection = (HttpURLConnection) url.openConnection();
        }
        connection.setRequestMethod("GET");

        is = connection.getInputStream();
        // check http status code
        if (connection.getResponseCode() == 200) {
            DataInputStream dis = new DataInputStream(new BufferedInputStream(is));
            StringWriter writer = new StringWriter();
            IOUtils.copy(dis, writer, "UTF-8");
            if (writer.toString().contains(token)) {
                cookie = connection.getHeaderField("Set-Cookie");
                if (cookie == null)
                    cookie = "";
            } else {
                logger.info("URL " + url.getFile() + " returned code 200 but does not contain keyword '" + token
                        + "'");
                logger.debug("1000 first chars of response body: " + writer.toString().substring(0, 1000));
            }
        } else {
            logger.error("URL " + url.getFile() + " returned code " + connection.getResponseCode() + " : "
                    + connection.getResponseMessage());
            if (System.getProperty("http.proxyHost") != null) {
                logger.info("Using proxy=" + System.getProperty("http.proxyHost") + ":"
                        + System.getProperty("http.proxyPort"));
            }
        }
    } catch (IOException e) {
        logger.error("URL test failed: " + url.getFile() + " => " + e.getMessage() + " ("
                + e.getClass().getName() + ")");
        if (System.getProperty("http.proxyHost") != null) {
            logger.info("Using proxy=" + System.getProperty("http.proxyHost") + ":"
                    + System.getProperty("http.proxyPort"));
        }
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException ioe) {
            // just going to ignore this one
        }
    }
    return cookie;

}

From source file:org.apache.jmeter.protocol.http.control.TestHTTPMirrorThread.java

public void testQueryRedirect() throws Exception {
    URL url = new URI("http", null, "localhost", HTTP_SERVER_PORT, "/path", "redirect=/a/b/c/d?q", null)
            .toURL();/*w  ww .j  a va 2s.  c o m*/
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setInstanceFollowRedirects(false);
    conn.connect();
    assertEquals(302, conn.getResponseCode());
    assertEquals("Temporary Redirect", conn.getResponseMessage());
    assertEquals("/a/b/c/d?q", conn.getHeaderField("Location"));
}

From source file:org.apache.jmeter.protocol.http.control.TestHTTPMirrorThread.java

public void testHeaders() throws Exception {
    URL url = new URL("http", "localhost", HTTP_SERVER_PORT, "/");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("X-SetHeaders", "Location: /abcd|X-Dummy: none");
    conn.connect();/*from   w  ww  .j a va2s.c  om*/
    assertEquals(200, conn.getResponseCode());
    assertEquals("OK", conn.getResponseMessage());
    assertEquals("/abcd", conn.getHeaderField("Location"));
    assertEquals("none", conn.getHeaderField("X-Dummy"));
}