Example usage for java.net HttpURLConnection getResponseCode

List of usage examples for java.net HttpURLConnection getResponseCode

Introduction

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

Prototype

public int getResponseCode() throws IOException 

Source Link

Document

Gets the status code from an HTTP response message.

Usage

From source file:com.richmond.riddler.AbstractGetNameTask.java

/**
 * Contacts the user info server to get the profile of the user and extracts the first name
 * of the user from the profile. In order to authenticate with the user info server the method
 * first fetches an access token from Google Play services.
 * @throws IOException if communication with user info server failed.
 * @throws JSONException if the response from the server could not be parsed.
 *//*from   ww w. j  a v  a 2  s.  c om*/
private void fetchNameFromProfileServer() throws IOException, JSONException {
    String token = fetchToken();
    if (token == null) {
        // error has already been handled in fetchToken()
        return;
    }
    URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
        InputStream is = con.getInputStream();
        mName = getFirstName(readResponse(is));
        //mActivity.setName(name);
        mActivity.show("Hello " + mName + "!");
        setAuth(true);
        is.close();
        return;
    } else if (sc == 401) {
        GoogleAuthUtil.invalidateToken(mActivity, token);
        onError("Server auth error, please try again.", null);
        Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream()));
        return;
    } else {
        onError("Server returned the following error code: " + sc, null);
        return;
    }
}

From source file:com.starit.diamond.server.service.TimerTaskService.java

public int checkStatusCode(String sURL) {
    try {/*from w  w w . j av a 2s  .co m*/
        URL url = new URL(sURL);

        URLConnection conn = url.openConnection();
        if (conn instanceof HttpURLConnection) {
            HttpURLConnection httpUrl = (HttpURLConnection) conn;
            return httpUrl.getResponseCode();
        }
        return -1;
    } catch (Exception e) {
        return -1;
    }
}

From source file:com.mingsoft.weixin.http.HttpClientConnectionManager.java

/**
 * ?/*from w w  w.  j  av a2s . com*/
 * @param postUrl ?
 * @param param ?
 * @param method 
 * @return null
 */
public static String request(String postUrl, String param, String method) {
    URL url;
    try {
        url = new URL(postUrl);

        HttpURLConnection conn;
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(30000); // ??)
        conn.setReadTimeout(30000); // ????)
        conn.setDoOutput(true); // post??http?truefalse
        conn.setDoInput(true); // ?httpUrlConnectiontrue
        conn.setUseCaches(false); // Post ?
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestMethod(method);// "POST"GET
        conn.setRequestProperty("Content-Length", param.length() + "");
        String encode = "utf-8";
        OutputStreamWriter out = null;
        out = new OutputStreamWriter(conn.getOutputStream(), encode);
        out.write(param);
        out.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return null;
        }
        // ??
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String line = "";
        StringBuffer strBuf = new StringBuffer();
        while ((line = in.readLine()) != null) {
            strBuf.append(line).append("\n");
        }
        in.close();
        out.close();
        return strBuf.toString();
    } catch (MalformedURLException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:com.relurori.sandbox.spreadsheet.gdata.AbstractGetNameTask.java

/**
 * Contacts the user info server to get the profile of the user and extracts the first name
 * of the user from the profile. In order to authenticate with the user info server the method
 * first fetches an access token from Google Play services.
 * @throws IOException if communication with user info server failed.
 * @throws JSONException if the response from the server could not be parsed.
 *//*from w  w w  .  j  ava  2  s .  co  m*/
private void fetchNameFromProfileServer() throws IOException, JSONException {
    Log.d(TAG, "fetchNameFromProfileServer");

    String token = fetchToken();
    if (token == null) {
        // error has already been handled in fetchToken()
        return;
    }
    URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
        InputStream is = con.getInputStream();
        String name = getFirstName(readResponse(is));
        mActivity.show("Hello " + name + "!");
        is.close();
        return;
    } else if (sc == 401) {
        GoogleAuthUtil.invalidateToken(mActivity, token);
        onError("Server auth error, please try again.", null);
        Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream()));
        return;
    } else {
        onError("Server returned the following error code: " + sc, null);
        return;
    }
}

From source file:com.dv.Utils.DvFileUtil.java

/**
 * ???xx.??./* w  w w  .  ja  va  2s  .  co  m*/
 * @param connection 
 * @return ??
 */
public static String getRealFileName(HttpURLConnection connection) {
    String name = null;
    try {
        if (connection == null) {
            return name;
        }
        if (connection.getResponseCode() == 200) {
            for (int i = 0;; i++) {
                String mime = connection.getHeaderField(i);
                if (mime == null) {
                    break;
                }
                // "Content-Disposition","attachment; filename=1.txt"
                // Content-Length
                if ("content-disposition".equals(connection.getHeaderFieldKey(i).toLowerCase())) {
                    Matcher m = Pattern.compile(".*filename=(.*)").matcher(mime.toLowerCase());
                    if (m.find()) {
                        return m.group(1).replace("\"", "");
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        DvLogUtil.e(DvFileUtil.class, "???");
    }
    return name;
}

From source file:org.cytoscape.app.internal.net.server.ScreenOriginsBeforeResponseTest.java

@Test
public void testScreenOrigins() throws Exception {
    final CyHttpd httpd = (new CyHttpdFactoryImpl()).createHttpd(new LocalhostServerSocketFactory(2609));
    final CyHttpResponseFactory responseFactory = new CyHttpResponseFactoryImpl();
    httpd.addResponder(new CyHttpResponder() {
        public Pattern getURIPattern() {
            return Pattern.compile("^/test$");
        }//from   ww  w .j  av  a 2s  .  com

        public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) {
            return responseFactory.createHttpResponse(HttpStatus.SC_OK, "test response ok", "text/html");
        }
    });
    httpd.addBeforeResponse(new ScreenOriginsBeforeResponse("http://x", "http://y"));
    httpd.start();

    HttpURLConnection connection = null;
    final String url = "http://localhost:2609/test";

    connection = connectToURL(url, "GET", null);
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN);

    connection = connectToURL(url, "GET", "http://x");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);

    connection = connectToURL(url, "GET", "http://y");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);

    connection = connectToURL(url, "GET", "http://z");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN);

    httpd.stop();
}

From source file:org.apache.hive.service.server.TestHS2HttpServer.java

@Test
public void testStackServlet() throws Exception {
    String baseURL = "http://localhost:" + webUIPort + "/stacks";
    URL url = new URL(baseURL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    boolean contents = false;
    String line;/*from   w  w w.j a  va  2s  . c o  m*/
    while ((line = reader.readLine()) != null) {
        if (line.contains("Process Thread Dump:")) {
            contents = true;
        }
    }
    Assert.assertTrue(contents);
}

From source file:org.cytoscape.app.internal.net.server.OriginOptionsBeforeResponseTest.java

@Test
public void testOptions() throws Exception {
    final CyHttpd httpd = (new CyHttpdFactoryImpl()).createHttpd(new LocalhostServerSocketFactory(2610));
    final CyHttpResponseFactory responseFactory = new CyHttpResponseFactoryImpl();
    httpd.addResponder(new CyHttpResponder() {
        public Pattern getURIPattern() {
            return Pattern.compile("^/test$");
        }/* w  w w.  j a  v a2 s  .  c o m*/

        public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) {
            return responseFactory.createHttpResponse(HttpStatus.SC_OK, "test response ok", "text/html");
        }
    });
    httpd.addBeforeResponse(new OriginOptionsBeforeResponse());
    httpd.start();

    HttpURLConnection connection = null;
    final String url = "http://localhost:2610/test";

    connection = connectToURL(url, "OPTIONS");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);
    assertEquals(connection.getHeaderField("Access-Control-Allow-Origin"), "*");
    assertEquals(connection.getHeaderField("Access-Control-Allow-Methods"), "POST, PUT, GET, OPTIONS");
    assertEquals(connection.getHeaderField("Access-Control-Max-Age"), "1");
    assertEquals(connection.getHeaderField("Access-Control-Allow-Headers"), "origin, accept");

    connection = connectToURL(url, "GET");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);
    assertEquals(readConnection(connection), "test response ok");

    httpd.stop();
}

From source file:io.sloeber.core.managers.Manager.java

/**
 * copy a url locally taking into account redirections
 *
 * @param url/*from  ww w  .ja  v  a2s  . c o m*/
 * @param localFile
 */
@SuppressWarnings("nls")
private static void myCopy(URL url, File localFile) {
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(5000);
        conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
        conn.addRequestProperty("User-Agent", "Mozilla");
        conn.addRequestProperty("Referer", "google.com");

        // normally, 3xx is redirect
        int status = conn.getResponseCode();

        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER)

                Files.copy(new URL(conn.getHeaderField("Location")).openStream(), localFile.toPath(),
                        REPLACE_EXISTING);
        } else {
            Files.copy(url.openStream(), localFile.toPath(), REPLACE_EXISTING);
        }

    } catch (Exception e) {
        Common.log(new Status(IStatus.WARNING, Activator.getId(), "Failed to download url " + url, e));
    }
}

From source file:org.cytoscape.app.internal.net.server.CyHttpdImplTest.java

@Test
public void testHttpd() throws Exception {
    final CyHttpd httpd = (new CyHttpdFactoryImpl()).createHttpd(new LocalhostServerSocketFactory(2608));
    final CyHttpResponseFactory responseFactory = new CyHttpResponseFactoryImpl();
    httpd.addResponder(new CyHttpResponder() {
        public Pattern getURIPattern() {
            return Pattern.compile("^/testA$");
        }//from w  w  w  .  j a v  a2  s . com

        public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) {
            return responseFactory.createHttpResponse(HttpStatus.SC_OK, "testA response ok", "text/html");
        }
    });

    httpd.addResponder(new CyHttpResponder() {
        public Pattern getURIPattern() {
            return Pattern.compile("^/testB$");
        }

        public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) {
            return responseFactory.createHttpResponse(HttpStatus.SC_OK, "testB response ok", "text/html");
        }
    });

    httpd.addBeforeResponse(new CyHttpBeforeResponse() {
        public CyHttpResponse intercept(CyHttpRequest request) {
            if (request.getMethod().equals("OPTIONS"))
                return responseFactory.createHttpResponse(HttpStatus.SC_OK, "options intercepted", "text/html");
            else
                return null;
        }
    });

    httpd.addAfterResponse(new CyHttpAfterResponse() {
        public CyHttpResponse intercept(CyHttpRequest request, CyHttpResponse response) {
            response.getHeaders().put("SomeRandomHeader", "WowInterceptWorks");
            return response;
        }
    });

    assertFalse(httpd.isRunning());
    httpd.start();
    assertTrue(httpd.isRunning());

    final String url = "http://localhost:2608/";

    // test if normal response works
    HttpURLConnection connection = connectToURL(url + "testA", "GET");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);
    assertEquals(readConnection(connection), "testA response ok");

    connection = connectToURL(url + "testB", "GET");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);
    assertEquals(readConnection(connection), "testB response ok");

    // test if 404 response works
    connection = connectToURL(url + "testX", "GET");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND);

    // test if before intercept works
    connection = connectToURL(url + "testA", "OPTIONS");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);
    assertEquals(readConnection(connection), "options intercepted");

    // test if after intercept works
    connection = connectToURL(url + "testA", "GET");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);
    assertEquals(connection.getHeaderField("SomeRandomHeader"), "WowInterceptWorks");

    httpd.stop();
    assertFalse(httpd.isRunning());
}