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:io.joynr.messaging.http.HttpMessageSender.java

public void sendMessage(final MessageContainer messageContainer, final FailureAction failureAction) {
    logger.trace("SEND messageId: {} channelId: {}", messageContainer.getMessageId(),
            messageContainer.getChannelId());

    HttpContext context = new BasicHttpContext();

    String channelId = messageContainer.getChannelId();
    String messageId = messageContainer.getMessageId();

    if (messageContainer.isExpired()) {
        logger.error("SEND executionQueue.run channelId: {}, messageId: {} TTL expired: ", messageId,
                messageContainer.getExpiryDate());
        failureAction.execute(new JoynrTimeoutException(messageContainer.getExpiryDate()));
        return;/*  w w w .j a v  a2  s.c om*/
    }

    // execute http command to send
    CloseableHttpResponse response = null;
    String sendUrl = null;
    try {

        String serializedMessage = messageContainer.getSerializedMessage();
        sendUrl = urlResolver.getSendUrl(messageContainer.getChannelId());
        logger.debug("SENDING message channelId: {}, messageId: {} toUrl: {}",
                new String[] { channelId, messageId, sendUrl });
        if (sendUrl == null) {
            logger.error("SEND executionQueue.run channelId: {}, messageId: {} No channelId found", messageId,
                    messageContainer.getExpiryDate());
            failureAction.execute(new JoynrMessageNotSentException("no channelId found"));
            return;
        }

        HttpPost httpPost = httpRequestFactory.createHttpPost(URI.create(sendUrl));
        httpPost.addHeader(new BasicHeader(httpConstants.getHEADER_CONTENT_TYPE(),
                httpConstants.getAPPLICATION_JSON() + ";charset=UTF-8"));
        httpPost.setEntity(new StringEntity(serializedMessage, "UTF-8"));

        // Clone the default config
        Builder requestConfigBuilder = RequestConfig.copy(defaultRequestConfig);
        requestConfigBuilder.setConnectionRequestTimeout(httpConstants.getSEND_MESSAGE_REQUEST_TIMEOUT());
        httpPost.setConfig(requestConfigBuilder.build());

        response = httpclient.execute(httpPost, context);

        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        String statusText = statusLine.getReasonPhrase();

        switch (statusCode) {
        case HttpURLConnection.HTTP_OK:
        case HttpURLConnection.HTTP_CREATED:
            logger.debug("SEND to ChannelId: {} messageId: {} completed successfully", channelId, messageId);
            break;
        case HttpURLConnection.HTTP_BAD_REQUEST:
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                logger.error(
                        "SEND to ChannelId: {} messageId: {} completed in error. No further reason found in message body",
                        channelId, messageId);
                return;
            }
            String body = EntityUtils.toString(entity, "UTF-8");

            JoynrMessagingError error = objectMapper.readValue(body, JoynrMessagingError.class);
            JoynrMessagingErrorCode joynrMessagingErrorCode = JoynrMessagingErrorCode
                    .getJoynrMessagingErrorCode(error.getCode());
            logger.error(error.toString());
            switch (joynrMessagingErrorCode) {
            case JOYNRMESSAGINGERROR_CHANNELNOTFOUND:
                failureAction.execute(new JoynrChannelMissingException("Channel does not exist. Status: "
                        + statusCode + " error: " + error.getCode() + "reason:" + error.getReason()));
                break;
            default:
                logger.error("SEND error channelId: {}, messageId: {} url: {} error: {} code: {} reason: {} ",
                        new Object[] { channelId, messageId, sendUrl, statusText, error.getCode(),
                                error.getReason() });
                failureAction.execute(new JoynrCommunicationException("Http Error while communicating: "
                        + statusText + body + " error: " + error.getCode() + "reason:" + error.getReason()));
                break;
            }
            break;
        default:
            logger.error("SEND to ChannelId: {} messageId: {} - unexpected response code: {} reason: {}",
                    new Object[] { channelId, messageId, statusCode, statusText });
            break;
        }
    } catch (Exception e) {
        // An exception occured - this could still be a communication error (e.g Connection refused)
        logger.error("SEND error channelId: {}, messageId: {} url: {} error: {}",
                new Object[] { channelId, messageId, sendUrl, e.getMessage() });

        failureAction.execute(new JoynrCommunicationException(
                e.getClass().getName() + "Exception while communicating. error: " + e.getMessage()));
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.letsgood.synergykitsdkandroid.requestmethods.PostFile.java

@Override
public BufferedReader execute() {
    String uri = null;/*w ww  .j ava2  s  . c om*/

    //init check
    if (!Synergykit.isInit()) {
        SynergykitLog.print(Errors.MSG_SK_NOT_INITIALIZED);

        statusCode = Errors.SC_SK_NOT_INITIALIZED;
        return null;
    }

    //URI check
    uri = getUri().toString();

    if (uri == null) {
        statusCode = Errors.SC_URI_NOT_VALID;
        return null;
    }

    //session token check
    if (sessionTokenRequired && sessionToken == null) {
        statusCode = Errors.SC_NO_SESSION_TOKEN;
        return null;
    }

    try {
        url = new URL(uri); // init url

        httpURLConnection = (HttpURLConnection) url.openConnection(); //open connection
        httpURLConnection.setConnectTimeout(CONNECT_TIMEOUT); //set connect timeout
        httpURLConnection.setReadTimeout(READ_TIMEOUT); //set read timeout
        httpURLConnection.setRequestMethod(REQUEST_METHOD); //set method
        httpURLConnection.addRequestProperty(PROPERTY_USER_AGENT, PROPERTY_USER_AGENT_VALUE); //set property accept
        httpURLConnection.addRequestProperty(PROPERTY_ACCEPT, ACCEPT_APPLICATION_VALUE); //set property accept
        httpURLConnection.addRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
        httpURLConnection.addRequestProperty("Connection", "Keep-Alive");
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);

        httpURLConnection.addRequestProperty(PROPERTY_AUTHORIZATION,
                "Basic " + Base64.encodeToString(
                        (Synergykit.getTenant() + ":" + Synergykit.getApplicationKey()).getBytes(),
                        Base64.NO_WRAP)); //set authorization

        if (Synergykit.getSessionToken() != null)
            httpURLConnection.addRequestProperty(PROPERTY_SESSION_TOKEN, Synergykit.getSessionToken());

        httpURLConnection.connect();

        //write data
        if (data != null) {
            dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());

            dataOutputStream.writeBytes(TWO_HYPHENS + BOUNDARY + CRLF);
            dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + ATTACHMENT_NAME
                    + "\";filename=\"" + ATTACHMENT_FILE_NAME + "\"" + CRLF);
            dataOutputStream.writeBytes(CRLF);
            dataOutputStream.write(data);
            dataOutputStream.writeBytes(CRLF);
            dataOutputStream.writeBytes(TWO_HYPHENS + BOUNDARY + TWO_HYPHENS + CRLF);
            dataOutputStream.flush();
            dataOutputStream.close();
        }

        statusCode = httpURLConnection.getResponseCode(); //get status code
        SynergykitLog.print(Integer.toString(statusCode));

        //read stream
        if (statusCode >= HttpURLConnection.HTTP_OK && statusCode < HttpURLConnection.HTTP_MULT_CHOICE) {
            return readStream(httpURLConnection.getInputStream());
        } else {
            return readStream(httpURLConnection.getErrorStream());
        }

    } catch (Exception e) {
        statusCode = HttpStatus.SC_SERVICE_UNAVAILABLE;
        e.printStackTrace();
        return null;
    }

}

From source file:net.sf.ehcache.constructs.web.AbstractWebTest.java

/**
 * Checks the response code is OK i.e. 200
 *
 * @param response/*from ww  w .j  ava  2s.  c o m*/
 */
protected void assertResponseOk(WebResponse response) {
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
}

From source file:mashberry.com500px.util.Api_Parser.java

/*******************************************************************************
  * /* w  w  w. j  a  v a2 s  .c  om*/
  *    (  )
  * 
  *******************************************************************************/
public static String get_second_detail(final int position, final String string, final int url_image_size,
        final int comments, final int comments_page) {
    String returnStr = "success";
    String urlStr = DB.Get_Photo_Url + "/" + string + "?image_size=" + url_image_size
    /*+ "&comments="   + comments
    + "&comments_page="   + comments_page*/
            + "&consumer_key=" + Var.consumer_key;
    try {
        URL url = new URL(urlStr);
        URLConnection uc = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) uc;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        httpConn.setConnectTimeout(10000);
        int response = httpConn.getResponseCode();

        if (response == HttpURLConnection.HTTP_OK) {
            InputStream in = httpConn.getInputStream();
            String userPictureOpt = "8";
            String result = convertStreamToString(in);
            JSONObject jObject = new JSONObject(result);
            JSONObject jsonObject = jObject.getJSONObject("photo");

            //            Log.i(TAG, "jsonObject " + jsonObject);

            Var.detail_nameMap.put(position, jsonObject.getString("name"));
            Var.detail_locationMap.put(position, jsonObject.getString("location"));
            Var.detail_ratingMap.put(position, jsonObject.getString("rating"));
            Var.detail_times_viewedMap.put(position, jsonObject.getString("times_viewed"));
            Var.detail_votesMap.put(position, jsonObject.getString("votes_count"));
            Var.detail_favoritesMap.put(position, jsonObject.getString("favorites_count"));
            Var.detail_descriptionMap.put(position, jsonObject.getString("description"));
            Var.detail_cameraMap.put(position, jsonObject.getString("camera"));
            Var.detail_lensMap.put(position, jsonObject.getString("lens"));
            Var.detail_focal_lengthMap.put(position, jsonObject.getString("focal_length"));
            Var.detail_isoMap.put(position, jsonObject.getString("iso"));
            Var.detail_shutter_speedMap.put(position, jsonObject.getString("shutter_speed"));
            Var.detail_apertureMap.put(position, jsonObject.getString("aperture"));
            Var.detail_categoryMap.put(position, jsonObject.getString("category"));
            Var.detail_uploadedMap.put(position, jsonObject.getString("hi_res_uploaded"));
            Var.detail_takenMap.put(position, jsonObject.getString("taken_at"));
            Var.detail_licenseTypeMap.put(position, jsonObject.getString("license_type"));

            JSONObject jsonuser = jsonObject.getJSONObject("user");
            Var.detail_user_nameMap.put(position, jsonuser.getString("fullname"));
            Var.detail_userpicMap.put(position, userPictureOpt + jsonuser.getString("userpic_url"));

            //     ( . .)
            /*JSONArray jsonArray = jObject.getJSONArray("comments");
            for(int i=0 ; i<jsonArray.length() ; i++){
               Var.comment_user_id.add(jsonArray.getJSONObject(i).getString("user_id"));
               Var.comment_body.add(jsonArray.getJSONObject(i).getString("body"));
                       
                JSONObject jsonuser = jsonArray.getJSONObject(i).getJSONObject("user");
                Var.comment_fullname.add(jsonuser.getString("fullname"));
                Var.comment_userpic_url.add(jsonuser.getString("userpic_url"));
            }*/

            /*            Log.i("Main", "feature   " +feature);
                        Log.i("Main", "filters   " +filters);
                        Log.i("Main", "categoryArr   " +Var.categoryArr);
                        Log.i("Main", "idArr   " +Var.idArr);
                        Log.i("Main", "image_urlArr   " +Var.image_urlArr);
                        Log.i("Main", "nameArr   " +Var.nameArr);
                        Log.i("Main", "ratingArr   " +Var.ratingArr);
                        Log.i("Main", "user_firstnameArr   " +Var.user_firstnameArr);
                        Log.i("Main", "user_fullnameArr   " +Var.user_fullnameArr);
                        Log.i("Main", "user_lastnameArr   " +Var.user_lastnameArr);
                        Log.i("Main", "user_upgrade_statusArr   " +Var.user_upgrade_statusArr);
                        Log.i("Main", "user_usernameArr   " +Var.user_usernameArr);
                        Log.i("Main", "user_userpic_urlArr   " +Var.user_userpic_urlArr);*/
        } else {
            returnStr = "not response";
            return returnStr;
        }
    } catch (Exception e) {
        e.printStackTrace();
        returnStr = "not response";
        return returnStr;
    }
    return returnStr;
}

From source file:org.exoplatform.shareextension.service.UploadAction.java

@Override
protected boolean doExecute() {
    String id = uploadInfo.uploadId;
    String boundary = "----------------------------" + id;
    String CRLF = "\r\n";
    int status = -1;
    OutputStream output = null;/*w ww. j a  v  a 2  s  .c  om*/
    PrintWriter writer = null;
    try {
        // Open a connection to the upload web service
        StringBuffer stringUrl = new StringBuffer(postInfo.ownerAccount.serverUrl).append("/portal")
                .append(ExoConstants.DOCUMENT_UPLOAD_PATH_REST).append("?uploadId=").append(id);
        URL uploadUrl = new URL(stringUrl.toString());
        HttpURLConnection uploadReq = (HttpURLConnection) uploadUrl.openConnection();
        uploadReq.setDoOutput(true);
        uploadReq.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        // Pass the session cookies for authentication
        CookieStore store = ExoConnectionUtils.cookiesStore;
        if (store != null) {
            StringBuffer cookieString = new StringBuffer();
            for (Cookie cookie : store.getCookies()) {
                cookieString.append(cookie.getName()).append("=").append(cookie.getValue()).append("; ");
            }
            uploadReq.addRequestProperty("Cookie", cookieString.toString());
        }
        ExoConnectionUtils.setUserAgent(uploadReq);
        // Write the form data
        output = uploadReq.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);
        writer.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"file\"; filename=\""
                + uploadInfo.fileToUpload.documentName + "\"").append(CRLF);
        writer.append("Content-Type: " + uploadInfo.fileToUpload.documentMimeType).append(CRLF);
        writer.append(CRLF).flush();
        byte[] buf = new byte[1024];
        while (uploadInfo.fileToUpload.documentData.read(buf) != -1) {
            output.write(buf);
        }
        output.flush();
        writer.append(CRLF).flush();
        writer.append("--" + boundary + "--").append(CRLF).flush();
        // Execute the connection and retrieve the status code
        status = uploadReq.getResponseCode();
    } catch (Exception e) {
        Log.e(LOG_TAG, "Error while uploading " + uploadInfo.fileToUpload, e);
    } finally {
        if (uploadInfo != null && uploadInfo.fileToUpload != null
                && uploadInfo.fileToUpload.documentData != null)
            try {
                uploadInfo.fileToUpload.documentData.close();
            } catch (IOException e1) {
                Log.e(LOG_TAG, "Error while closing the upload stream", e1);
            }
        if (output != null)
            try {
                output.close();
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error while closing the connection", e);
            }
        if (writer != null)
            writer.close();
    }
    if (status < HttpURLConnection.HTTP_OK || status >= HttpURLConnection.HTTP_MULT_CHOICE) {
        // Exit if the upload went wrong
        return listener.onError("Could not upload the file " + uploadInfo.fileToUpload.documentName);
    }
    status = -1;
    try {
        // Prepare the request to save the file in JCR
        String stringUrl = postInfo.ownerAccount.serverUrl + "/portal"
                + ExoConstants.DOCUMENT_CONTROL_PATH_REST;
        Uri moveUri = Uri.parse(stringUrl);
        moveUri = moveUri.buildUpon().appendQueryParameter("uploadId", id)
                .appendQueryParameter("action", "save")
                .appendQueryParameter("workspaceName", DocumentHelper.getInstance().workspace)
                .appendQueryParameter("driveName", uploadInfo.drive)
                .appendQueryParameter("currentFolder", uploadInfo.folder)
                .appendQueryParameter("fileName", uploadInfo.fileToUpload.documentName).build();
        HttpGet moveReq = new HttpGet(moveUri.toString());
        // Execute the request and retrieve the status code
        HttpResponse move = ExoConnectionUtils.httpClient.execute(moveReq);
        status = move.getStatusLine().getStatusCode();
    } catch (Exception e) {
        Log.e(LOG_TAG, "Error while saving " + uploadInfo.fileToUpload + " in JCR", e);
    }
    boolean ret = false;
    if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) {
        ret = listener.onSuccess("File " + uploadInfo.fileToUpload.documentName + "uploaded successfully");
    } else {
        ret = listener.onError("Could not save the file " + uploadInfo.fileToUpload.documentName);
    }
    return ret;
}

From source file:org.fedoraproject.eclipse.packager.bodhi.api.BodhiClient.java

@Override
public BodhiLoginResponse login(String username, String password) throws BodhiClientLoginException {
    BodhiLoginResponse result = null;/*from w  w  w .  j a  v  a 2  s  .  c  o  m*/
    try {
        HttpPost post = new HttpPost(getLoginUrl());
        // Add "Accept: application/json" HTTP header
        post.addHeader(ACCEPT_HTTP_HEADER_NAME, MIME_JSON);

        // Construct the multipart POST request body.
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart(LOGIN_PARAM_NAME, new StringBody(LOGIN_PARAM_VALUE));
        reqEntity.addPart(USERNAME_PARAM_NAME, new StringBody(username));
        reqEntity.addPart(PASSWORD_PARAM_NAME, new StringBody(password));

        post.setEntity(reqEntity);

        HttpResponse response = httpclient.execute(post);
        HttpEntity resEntity = response.getEntity();
        int returnCode = response.getStatusLine().getStatusCode();

        if (returnCode != HttpURLConnection.HTTP_OK) {
            throw new BodhiClientLoginException(NLS.bind("{0} {1}", response.getStatusLine().getStatusCode(), //$NON-NLS-1$
                    response.getStatusLine().getReasonPhrase()), response);
        } else {
            // Got a 200, response body is the JSON passed on from the
            // server.
            String jsonString = ""; //$NON-NLS-1$
            if (resEntity != null) {
                try {
                    jsonString = parseResponse(resEntity);
                } catch (IOException e) {
                    // ignore
                } finally {
                    EntityUtils.consume(resEntity); // clean up resources
                }
            }
            // log JSON string if in debug mode
            if (PackagerPlugin.inDebugMode()) {
                FedoraPackagerLogger logger = FedoraPackagerLogger.getInstance();
                logger.logInfo(NLS.bind(BodhiText.BodhiClient_rawJsonStringMsg, jsonString));
            }
            // Deserialize from JSON
            GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.registerTypeAdapter(DateTime.class, new DateTimeDeserializer());
            Gson gson = gsonBuilder.create();
            result = gson.fromJson(jsonString, BodhiLoginResponse.class);
        }
    } catch (IOException e) {
        throw new BodhiClientLoginException(e.getMessage(), e);
    }
    return result;
}

From source file:com.murrayc.galaxyzoo.app.provider.test.ZooniverseClientTest.java

public void testLoginWithFailure() throws IOException {
    final MockWebServer server = new MockWebServer();

    //On failure, the server's response code is HTTP_OK,
    //but it has a "success: false" parameter.
    final MockResponse response = new MockResponse();
    response.setResponseCode(HttpURLConnection.HTTP_OK);
    response.setBody("test nonsense failure message");
    server.enqueue(response);//from  www.ja  v  a 2  s . c o m
    server.play();

    final ZooniverseClient client = createZooniverseClient(server);

    try {
        final LoginUtils.LoginResult result = client.loginSync("testusername", "testpassword");
        assertNotNull(result);
        assertFalse(result.getSuccess());
    } catch (final ZooniverseClient.LoginException e) {
        assertTrue(e.getCause() instanceof MalformedJsonException);
    }

    server.shutdown();
}

From source file:com.example.android.wearable.wcldemo.pages.StockActivity.java

@Override
public void onHttpResponseReceived(String requestId, int status, String response) {
    Log.d(TAG, "Request Id: " + requestId + " Status: " + status + ", response: " + response);
    int toastMessageResource = 0;
    switch (status) {
    case HttpURLConnection.HTTP_OK:
        response = response.substring(3);
        try {/*from  w ww .j  av  a  2s.  c  om*/
            JSONArray jsonArray = new JSONArray(response);
            // parse the json response
            if (jsonArray.length() == 1) {
                JSONObject jsonObj = (JSONObject) jsonArray.get(0);
                final String symbol = jsonObj.getString("t");
                final double currentValue = jsonObj.getDouble("l_cur");
                final String time = jsonObj.getString("lt");
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        updateValues(symbol, currentValue + "", time);
                    }
                });
            }
        } catch (JSONException e) {
            Log.e(TAG, "Error parsing json", e);
            toastMessageResource = R.string.error_request_failed;
        }
        break;
    case WearHttpHelper.ERROR_REQUEST_FAILED:
        Log.e(TAG, "Request failed");
        toastMessageResource = R.string.error_request_failed;
        break;
    case WearHttpHelper.ERROR_TIMEOUT:
        Log.e(TAG, "Timeout happened while waiting for response");
        toastMessageResource = R.string.error_timeout;
        break;
    default:
        Log.e(TAG, "A non-successful status code: " + status + " was received");
        toastMessageResource = R.string.error_request_failed;
    }
    final int messageResource = toastMessageResource;
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            mProgressBar.setVisibility(View.GONE);
            if (messageResource > 0) {
                Toast.makeText(StockActivity.this, messageResource, Toast.LENGTH_SHORT).show();
            }
        }
    });
}

From source file:org.ow2.proactive_grid_cloud_portal.rm.RMRestTest.java

@Test
public void testShutdown_PreemptParameter() throws Exception {
    RMProxyUserInterface rm = mock(RMProxyUserInterface.class);
    when(rm.shutdown(true)).thenReturn(new BooleanWrapper(true));

    String sessionId = SharedSessionStoreTestUtils.createValidSession(rm);

    HttpResponse response = callHttpGetMethod("shutdown?preempt=true", sessionId);

    assertEquals(HttpURLConnection.HTTP_OK, response.getStatusLine().getStatusCode());
    verify(rm).shutdown(true);/*from   w  ww. ja v  a2 s.  c o m*/
}