Example usage for java.net HttpURLConnection HTTP_CREATED

List of usage examples for java.net HttpURLConnection HTTP_CREATED

Introduction

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

Prototype

int HTTP_CREATED

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

Click Source Link

Document

HTTP Status-Code 201: Created.

Usage

From source file:org.wso2.charon3.samples.group.sample01.CreateGroupSample.java

public static void main(String[] args) {
    try {//from  ww w  .  j a v a  2 s.c o m
        String url = "http://localhost:8080/scim/v2/Groups";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // Setting basic post request
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/scim+json");

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

        int responseCode = con.getResponseCode();

        BufferedReader in;
        if (responseCode == HttpURLConnection.HTTP_CREATED) { // success
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        } else {
            in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        }
        String inputLine;
        StringBuffer response = new StringBuffer();

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

        //printing result from response
        System.out.println("Response Code : " + responseCode);
        System.out.println("Response Message : " + con.getResponseMessage());
        System.out.println("Response Content : " + response.toString());

    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.charon3.samples.user.sample01.CreateUserSample.java

public static void main(String[] args) {
    try {/*  w  w  w  .j a  va2 s.com*/
        String url = "http://localhost:8080/scim/v2/Users";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // Setting basic post request
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/scim+json");

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

        int responseCode = con.getResponseCode();

        BufferedReader in;
        if (responseCode == HttpURLConnection.HTTP_CREATED) { // success
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        } else {
            in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        }
        String inputLine;
        StringBuffer response = new StringBuffer();

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

        //printing result from response
        System.out.println("Response Code : " + responseCode);
        System.out.println("Response Message : " + con.getResponseMessage());
        System.out.println("Response Content : " + response.toString());

    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.jboss.narayana.rts.TxnHelper.java

public static Set<Link> beginTxn(Client client, String txurl) throws IOException {
    Response response = null;// ww w.java  2s  .c  o  m

    try {
        response = client.target(txurl).request()
                .post(Entity.entity(new Form(), MediaType.APPLICATION_FORM_URLENCODED_TYPE));
        Set<Link> links = response.getLinks();

        EntityUtils.consume((HttpEntity) response.getEntity());
        if (response.getStatus() != HttpURLConnection.HTTP_CREATED)
            throw new RuntimeException("beginTxn returned " + response.getStatus());

        return links;
    } finally {
        if (response != null)
            response.close();
    }
}

From source file:com.couchbase.client.TestOperationPutImpl.java

@Override
public void handleResponse(HttpResponse response) {
    StringBuilder json = new StringBuilder(""); // workaround for null returns
    json.append(getEntityString(response));
    int errorcode = response.getStatusLine().getStatusCode();

    if (errorcode == HttpURLConnection.HTTP_CREATED) {
        ((TestCallback) callback).getData(json.toString());
        callback.receivedStatus(new OperationStatus(true, "OK"));
    } else {//from w  w  w.  j  a v  a 2  s . co  m
        callback.receivedStatus(new OperationStatus(false, Integer.toString(errorcode) + ": " + json));
    }
    callback.complete();
}

From source file:com.appdynamics.common.RESTClient.java

public static void sendPost(String urlString, String input, String apiKey) {
    try {/*w ww .j  a  v a 2  s .com*/
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");

        conn.setRequestProperty("Authorization",
                "Basic " + new String(Base64.encodeBase64((apiKey).getBytes())));

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

        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        logger.info("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            logger.info(output);
        }

        conn.disconnect();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

From source file:org.eclipse.orion.server.tests.performance.SimpleServerStressTest.java

@Test
public void testCreateProject() throws IOException, SAXException, JSONException {
    Performance performance = Performance.getDefault();
    PerformanceMeter meter = performance.createPerformanceMeter("SimpleServerStressTest#testCreateProject");
    //create workspace
    String workspaceName = SimpleServerStressTest.class.getName() + "#testCreateProject";
    createWorkspace(workspaceName);/*from  w w w  .j  a  v  a2  s  . c  o  m*/
    final int PROJECT_COUNT = 1000;//increase this value for a real stress test
    meter.start();
    long start = System.currentTimeMillis();
    for (int i = 0; i < PROJECT_COUNT; i++) {
        //create a project
        String projectName = "Project" + i;
        WebRequest request = getCreateProjectRequest(workspaceLocation, projectName, null);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
        String locationHeader = response.getHeaderField(ProtocolConstants.HEADER_LOCATION);
        assertNotNull(locationHeader);
        if (i % 500 == 0) {
            long end = System.currentTimeMillis();
            long avg = (end - start) / (i + 1);
            System.out.println("Created project " + i + " average time per project: " + avg);
        }
    }
    meter.stop();
    meter.commit();
}

From source file:com.psbk.modulperwalian.Controller.DosenController.java

public String getDataDosenTest() throws Exception {
    String nip = null;//from ww w  .  j a v  a  2s  .  c o  m
    URL url = new URL(BASE_URL + "dosen/apa/");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.addRequestProperty("Authorization", "Basic YWRtaW46YWRtaW4=");

    String input = "{\"id_dosen\"dos02\"}";

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

    if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
        throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
    }

    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {

        nip = output;
    }

    return output;
}

From source file:com.mobile.godot.core.controller.CoreController.java

public synchronized void approach(String username, String carName) {

    String servlet = "Approach";
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("username", username));
    params.add(new BasicNameValuePair("carName", carName));
    SparseIntArray mMessageMap = new SparseIntArray();
    mMessageMap.append(HttpURLConnection.HTTP_ACCEPTED, GodotMessage.Core.DRIVER_UPDATED);
    mMessageMap.append(HttpURLConnection.HTTP_CREATED, GodotMessage.Core.MESSAGE_SENT);
    mMessageMap.append(HttpURLConnection.HTTP_NOT_FOUND, GodotMessage.Core.CAR_NOT_FOUND);
    mMessageMap.append(HttpURLConnection.HTTP_UNAUTHORIZED, GodotMessage.Error.UNAUTHORIZED);

    GodotAction action = new GodotAction(servlet, params, mMessageMap, mHandler);
    Thread tAction = new Thread(action);
    tAction.start();/*www  . j  a v a  2 s .  com*/

}

From source file:org.eclipse.orion.server.tests.servlets.files.AdvancedFilesTest.java

@Test
public void testETagDeletedFile() throws JSONException, IOException, SAXException, CoreException {
    String fileName = "testfile.txt";

    //setup: create a file
    WebRequest request = getPostFilesRequest("", getNewFileJSON(fileName).toString(), fileName);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

    //obtain file metadata and ensure data is correct
    request = getGetFilesRequest(fileName + "?parts=meta");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    String etag = response.getHeaderField(ProtocolConstants.KEY_ETAG);
    assertNotNull(etag);/*  ww w  . j  a  va  2 s  . c  o m*/

    //delete the file on disk
    IFileStore fileStore = EFS.getStore(makeLocalPathAbsolute(fileName));
    fileStore.delete(EFS.NONE, null);

    //now a PUT should fail
    request = getPutFileRequest(fileName, "something");
    request.setHeaderField(ProtocolConstants.HEADER_IF_MATCH, etag);
    try {
        response = webConversation.getResponse(request);
    } catch (IOException e) {
        //inexplicably HTTPUnit throws IOException on PRECON_FAILED rather than just giving us response
        assertTrue(e.getMessage().indexOf(Integer.toString(HttpURLConnection.HTTP_PRECON_FAILED)) > 0);
    }
}

From source file:i5.las2peer.services.userManagement.UserManagement.java

/**
 * //w ww  . jav a 2 s .  c o  m
 * createUser
 * 
 * 
 * @return HttpResponse
 * 
 */
@POST
@Path("/create")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = "userExists"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "authorizationNeeded"),
        @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "userCreated"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "internal"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "malformedRequest") })
@ApiOperation(value = "createUser", notes = "")
public HttpResponse createUser() {
    // userExists
    boolean userExists_condition = true;
    if (userExists_condition) {
        String error = "Some String";
        HttpResponse userExists = new HttpResponse(error, HttpURLConnection.HTTP_CONFLICT);
        return userExists;
    }
    // authorizationNeeded
    boolean authorizationNeeded_condition = true;
    if (authorizationNeeded_condition) {
        String error = "Some String";
        HttpResponse authorizationNeeded = new HttpResponse(error, HttpURLConnection.HTTP_UNAUTHORIZED);
        return authorizationNeeded;
    }
    // userCreated
    boolean userCreated_condition = true;
    if (userCreated_condition) {
        JSONObject User = new JSONObject();
        HttpResponse userCreated = new HttpResponse(User.toJSONString(), HttpURLConnection.HTTP_CREATED);
        return userCreated;
    }
    // internal
    boolean internal_condition = true;
    if (internal_condition) {
        String error = "Some String";
        HttpResponse internal = new HttpResponse(error, HttpURLConnection.HTTP_INTERNAL_ERROR);
        return internal;
    }
    // malformedRequest
    boolean malformedRequest_condition = true;
    if (malformedRequest_condition) {
        String malformation = "Some String";
        HttpResponse malformedRequest = new HttpResponse(malformation, HttpURLConnection.HTTP_BAD_REQUEST);
        return malformedRequest;
    }
    return null;
}