Example usage for java.net HttpURLConnection HTTP_OK

List of usage examples for java.net HttpURLConnection HTTP_OK

Introduction

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

Prototype

int HTTP_OK

To view the source code for java.net HttpURLConnection HTTP_OK.

Click Source Link

Document

HTTP Status-Code 200: OK.

Usage

From source file:com.jeremyhaberman.playgrounds.WebPlaygroundDAO.java

@Override
public Collection<Playground> getAll(Context context) {
    // synchronized (Swingset.initPlaygroundLock) {
    playgrounds = new ArrayList<Playground>();
    String result = swingset.getResources().getString(R.string.error);
    HttpURLConnection httpConnection = null;
    Log.d(TAG, "getPlaygrounds()");

    try {/* ww  w  . j  ava 2  s  .c o  m*/
        // Check if task has been interrupted
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        // Build query
        URL url = new URL("http://swingsetweb.appspot.com/playground");
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(15000);
        httpConnection.setReadTimeout(15000);
        StringBuilder response = new StringBuilder();

        if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // Read results from the query
            BufferedReader input = new BufferedReader(
                    new InputStreamReader(httpConnection.getInputStream(), "UTF-8"));
            String strLine = null;
            while ((strLine = input.readLine()) != null) {
                response.append(strLine);
            }
            input.close();

        }

        // Parse to get translated text
        JSONArray jsonPlaygrounds = new JSONArray(response.toString());
        int numOfPlaygrounds = jsonPlaygrounds.length();

        JSONObject jsonPlayground = null;

        for (int i = 0; i < numOfPlaygrounds; i++) {
            jsonPlayground = jsonPlaygrounds.getJSONObject(i);
            playgrounds.add(toPlayground(jsonPlayground));
        }

    } catch (Exception e) {
        Log.e(TAG, "Exception", e);
        Intent errorIntent = new Intent(context, Playgrounds.class);
        errorIntent.putExtra("Exception", e.getLocalizedMessage());
        errorIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(errorIntent);
    } finally {
        if (httpConnection != null) {
            httpConnection.disconnect();
        }
    }

    // all done
    Log.d(TAG, "   -> returned " + result);
    return playgrounds;
    // }
}

From source file:i5.las2peer.services.todolist.Todolist.java

/**
 * //from w w w .  j  a  v a2  s  .  c om
 * createData
 * 
 * 
 * @return HttpResponse
 * 
 */
@POST
@Path("/data/{name}")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "responseCreateData") })
@ApiOperation(value = "createData", notes = "")
public HttpResponse createData(@PathParam("name") String name) {
    Connection conn = null;
    try {

        conn = dbm.getConnection();
        PreparedStatement stmt = conn
                .prepareStatement("INSERT INTO gamificationCAE.todolist (name) VALUES (?)");
        stmt.setString(1, name);

        stmt.executeUpdate();

        return new HttpResponse(name + " is added!", HttpURLConnection.HTTP_OK);

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

        return new HttpResponse("Database connection error", HttpURLConnection.HTTP_INTERNAL_ERROR);
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:net.gcolin.simplerepo.test.AbstractRepoTest.java

protected String getContent(String url, long lastUpdate) throws IOException {
    HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
    try {//from  ww  w. ja v a2  s .  c o m
        if (lastUpdate > 0) {
            c.setIfModifiedSince(lastUpdate);
        }
        c.setUseCaches(false);
        c.connect();
        return c.getResponseCode() == HttpURLConnection.HTTP_OK
                ? new String(IOUtils.toByteArray(c.getInputStream()), "utf-8")
                : null;
    } finally {
        c.disconnect();
    }
}

From source file:i5.las2peer.services.servicePackage.TemplateService.java

/**
 * Simple function to validate a user login.
 * Basically it only serves as a "calling point" and does not really validate a user
 * (since this is done previously by LAS2peer itself, the user does not reach this method
 * if he or she is not authenticated)./*www .ja  va 2 s  .  c o  m*/
 * 
 */
@GET
@Path("/validation")
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(value = "User Validation", notes = "Simple function to validate a user login.")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Validation Confirmation"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
public HttpResponse validateLogin() {
    String returnString = "";
    returnString += "You are " + ((UserAgent) getActiveAgent()).getLoginName() + " and your login is valid!";

    return new HttpResponse(returnString, HttpURLConnection.HTTP_OK);
}

From source file:com.sun.socialsite.pojos.App.java

public static App readFromURL(URL url) throws Exception {
    HttpURLConnection con = (HttpURLConnection) (url.openConnection());
    con.setDoOutput(false);//from w ww . ja  v a2  s .  co  m
    // TODO: figure out why this is necessary for HTTPS URLs
    if (con instanceof HttpsURLConnection) {
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) {
                    return true;
                } else {
                    log.warn("URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                    return false;
                }
            }
        };
        ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv);
    }
    con.connect();
    if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new RuntimeException(con.getResponseMessage());
    }
    InputStream in = con.getInputStream();
    return readFromStream(in, url);
}

From source file:com.openforevent.main.UserPosition.java

public static Map<String, Object> userLocationProperties(DispatchContext ctx,
        Map<String, ? extends Object> context) throws IOException {
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();
    String visitId = (String) context.get("visitId");

    if (Debug.infoOn()) {
        Debug.logInfo("In userLocationProperties", module);
    }/*from ww  w. java  2 s.c o  m*/

    // get user coords
    coordsOfUserPosition(ctx, context);

    URL url = new URL(
            "https://graph.facebook.com/search?since=now&limit=4&q=2012-05-07&type=event&access_token="
                    + "AAACEdEose0cBAN9CB2ErxVN3JvK2gsrLslPt6e6Y7hJ0OrMEkMoyNwvHgSZCAEu2lCHZALlVWXZCW5JL8asMWoaPN3UAXFpZBsJJ6SvXRAAIZAXeTo0fD");
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    // Set properties of the connection
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // Retrieve the output
    int responseCode = urlConnection.getResponseCode();
    InputStream inputStream;
    if (responseCode == HttpURLConnection.HTTP_OK) {
        inputStream = urlConnection.getInputStream();
    } else {
        inputStream = urlConnection.getErrorStream();
    }

    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, "UTF-8");
    String theString = writer.toString();

    Debug.logInfo("Facebook stream = ", theString);

    if (theString.contains("AuthException") == true) {
        url = new URL("https://graph.facebook.com/oauth/access_token?" + "client_id=   283576871735609&"
                + "client_secret=   5cf1fe4e531dff8de228bfac61b8fdfa&" + "grant_type=fb_exchange_token&"
                + "fb_exchange_token="
                + "AAACEdEose0cBAN9CB2ErxVN3JvK2gsrLslPt6e6Y7hJ0OrMEkMoyNwvHgSZCAEu2lCHZALlVWXZCW5JL8asMWoaPN3UAXFpZBsJJ6SvXRAAIZAXeTo0fD");

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

        // Set properties of the connection
        urlConnection1.setRequestMethod("GET");
        urlConnection1.setDoInput(true);
        urlConnection1.setDoOutput(true);
        urlConnection1.setUseCaches(false);
        urlConnection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        // Retrieve the output
        int responseCode1 = urlConnection1.getResponseCode();
        InputStream inputStream1;
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inputStream1 = urlConnection1.getInputStream();
        } else {
            inputStream1 = urlConnection1.getErrorStream();
        }

        StringWriter writer1 = new StringWriter();
        IOUtils.copy(inputStream1, writer1, "UTF-8");
        String theString1 = writer1.toString();

        Debug.logInfo("Facebook stream1 = ", theString1);

    }

    Map<String, Object> paramOut = FastMap.newInstance();
    paramOut.put("geoName", "aaa");
    paramOut.put("abbreviation", "bbb");
    return paramOut;

}

From source file:com.reactivetechnologies.jaxrs.RestServerTest.java

static String sendDelete(String url, String content) throws IOException {

    StringBuilder response = new StringBuilder();
    HttpURLConnection con = null;
    BufferedReader in = null;/*www .j a va2  s .co  m*/
    try {
        URL obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("DELETE");

        //add request header
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeUTF(content);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        } else {
            throw new IOException("Response Code: " + responseCode);
        }

        return response.toString();
    } catch (IOException e) {
        throw e;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {

            }
        }
        if (con != null) {
            con.disconnect();
        }
    }

}

From source file:bluevia.SendSMS.java

public static void setFacebookWallPost(String userEmail, String post) {
    try {/*from w  ww  . j a 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:org.cm.podd.report.util.RequestDataUtil.java

public static ResponseObject get(String path, String query, String token) {
    JSONObject jsonObj = null;//from   w w w  .j a v a2s  . co  m
    String rawData = null;
    int statusCode = 0;

    //SharedPreferences settings = PoddApplication.getAppContext().getSharedPreferences("PoddPrefsFile", 0);
    String serverUrl = settings.getString("serverUrl", BuildConfig.SERVER_URL);

    String reqUrl = "";
    if (path.contains("http://") || path.contains("https://")) {
        reqUrl = String.format("%s%s", path, query == null ? "" : "?" + query);
    } else {
        reqUrl = String.format("%s%s%s", serverUrl, path, query == null ? "" : "?" + query);
    }
    Log.i(TAG, "submit url=" + reqUrl);

    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpClient client = new DefaultHttpClient(params);

    try {
        HttpGet get = new HttpGet(reqUrl);
        if (token != null) {
            get.setHeader("Authorization", "Token " + token);
        }

        HttpResponse response;
        response = client.execute(get);
        HttpEntity entity = response.getEntity();

        // Detect server complaints
        statusCode = response.getStatusLine().getStatusCode();
        Log.v(TAG, "status code=" + statusCode);

        if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED) {
            InputStream in = entity.getContent();
            rawData = FileUtil.convertInputStreamToString(in);

            entity.consumeContent();
        }

    } catch (ClientProtocolException e) {
        Log.e(TAG, "error post data", e);
    } catch (IOException e) {
        Log.e(TAG, "Can't connect server", e);
    } finally {
        client.getConnectionManager().shutdown();
    }

    ResponseObject respObj = new ResponseObject(statusCode, jsonObj);
    respObj.setRawData(rawData);
    return respObj;
}

From source file:com.sk89q.squirrelid.util.HttpRequest.java

/**
 * Execute the request./*from  w w w.j av a 2 s . c  om*/
 * <p/>
 * After execution, {@link #close()} should be called.
 *
 * @return this object
 * @throws java.io.IOException on I/O error
 */
public HttpRequest execute() throws IOException {
    boolean successful = false;

    try {
        if (conn != null) {
            throw new IllegalArgumentException("Connection already executed");
        }

        conn = (HttpURLConnection) reformat(url).openConnection();

        if (body != null) {
            conn.setRequestProperty("Content-Type", contentType);
            conn.setRequestProperty("Content-Length", Integer.toString(body.length));
            conn.setDoInput(true);
        }

        for (Map.Entry<String, String> entry : headers.entrySet()) {
            conn.setRequestProperty(entry.getKey(), entry.getValue());
        }

        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setReadTimeout(READ_TIMEOUT);

        conn.connect();

        if (body != null) {
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.write(body);
            out.flush();
            out.close();
        }

        inputStream = conn.getResponseCode() == HttpURLConnection.HTTP_OK ? conn.getInputStream()
                : conn.getErrorStream();

        successful = true;
    } finally {
        if (!successful) {
            close();
        }
    }

    return this;
}