List of usage examples for java.net HttpURLConnection HTTP_OK
int HTTP_OK
To view the source code for java.net HttpURLConnection HTTP_OK.
Click Source Link
From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientImplTest.java
@Test public void testRetryOnMissingHttpResponse() throws Exception { final byte[] requestBytes = "fake_request".getBytes(UTF_8); final CloseableHttpResponse badResponse = mock(CloseableHttpResponse.class); final CloseableHttpResponse goodResponse = mock(CloseableHttpResponse.class); final StatusLine badStatusLine = mock(StatusLine.class); final StatusLine goodStatusLine = mock(StatusLine.class); final StringEntity responseEntity = new StringEntity("success"); final Answer<CloseableHttpResponse> failThenSucceed = new Answer<CloseableHttpResponse>() { private int iteration = 0; @Override//from w w w .j a v a 2 s. c om public CloseableHttpResponse answer(InvocationOnMock invocation) throws Throwable { iteration++; if (1 == iteration) { throw new NoHttpResponseException("The server didn't respond!"); } else { return goodResponse; } } }; final AvaticaCommonsHttpClientImpl client = mock(AvaticaCommonsHttpClientImpl.class); when(client.send(any(byte[].class))).thenCallRealMethod(); when(client.execute(any(HttpPost.class), any(HttpClientContext.class))).then(failThenSucceed); when(badResponse.getStatusLine()).thenReturn(badStatusLine); when(badStatusLine.getStatusCode()).thenReturn(HttpURLConnection.HTTP_UNAVAILABLE); when(goodResponse.getStatusLine()).thenReturn(goodStatusLine); when(goodStatusLine.getStatusCode()).thenReturn(HttpURLConnection.HTTP_OK); when(goodResponse.getEntity()).thenReturn(responseEntity); byte[] responseBytes = client.send(requestBytes); assertEquals("success", new String(responseBytes, UTF_8)); }
From source file:com.polyvi.xface.extension.advancedfiletransfer.FileDownloader.java
/** * ??(?????/*from ww w. jav a2s . c o m*/ * ??????) */ private void initDownloadInfo() { int totalSize = 0; if (isFirst(mUrl)) { HttpURLConnection connection = null; try { URL url = new URL(mUrl); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(TIME_OUT_MILLISECOND); connection.setRequestMethod("GET"); System.getProperties().setProperty("http.nonProxyHosts", url.getHost()); // cookie? setCookieProperty(connection, mUrl); if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) { totalSize = connection.getContentLength(); if (-1 != totalSize) { mDownloadInfo = new FileDownloadInfo(totalSize, 0, mUrl); // ?mDownloadInfo?? mFileTransferRecorder.saveDownloadInfo(mDownloadInfo); } else { XLog.e(CLASS_NAME, "cannot get totalSize"); } // temp File file = new File(mLocalFilePath + TEMP_FILE_SUFFIX); if (file.exists()) { file.delete(); } } } catch (IOException e) { XLog.e(CLASS_NAME, e.getMessage()); } finally { if (null != connection) { connection.disconnect(); } } } else { // ?url? mDownloadInfo = mFileTransferRecorder.getDownloadInfo(mUrl); totalSize = mDownloadInfo.getTotalSize(); mDownloadInfo.setCompleteSize(getCompleteSize(mLocalFilePath + TEMP_FILE_SUFFIX)); } mBufferSize = getSingleTransferLength(totalSize); }
From source file:i5.las2peer.services.userManagement.UserManagement.java
/** * /*from w w w . j a v a 2 s .co m*/ * getUser * * * @return HttpResponse * */ @GET @Path("/get") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.TEXT_PLAIN) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "userFound"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "internal"), @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "userNotFound") }) @ApiOperation(value = "getUser", notes = "") public HttpResponse getUser() { // userFound boolean userFound_condition = true; if (userFound_condition) { JSONObject user = new JSONObject(); HttpResponse userFound = new HttpResponse(user.toJSONString(), HttpURLConnection.HTTP_OK); return userFound; } // internal boolean internal_condition = true; if (internal_condition) { String error = "Some String"; HttpResponse internal = new HttpResponse(error, HttpURLConnection.HTTP_INTERNAL_ERROR); return internal; } // userNotFound boolean userNotFound_condition = true; if (userNotFound_condition) { String error = "Some String"; HttpResponse userNotFound = new HttpResponse(error, HttpURLConnection.HTTP_NOT_FOUND); return userNotFound; } return null; }
From source file:com.edgenius.wiki.service.impl.NotifyMQConsumer.java
public void handleMessage(Object msg) { NotifyMQObject mqObj;/*from w ww.j a va 2 s . co m*/ try { if (msg instanceof NotifyMQObject) { mqObj = (NotifyMQObject) msg; if (mqObj.getType() == NotifyMQObject.TYPE_SYSTEM_STATUS_CHECK) { //send a http response to confirm JMS received String url = WebUtil.getHostAppURL() + "status?uuid=" + mqObj.getSpaceUname(); try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(20000); if (log.isDebugEnabled()) { String uuid = IOUtils.toString(conn.getInputStream()); log.debug("Recieved system status JMS check UUID {}", uuid); } if (HttpURLConnection.HTTP_OK != conn.getResponseCode()) { log.warn("Unable get response from system status JMS confirm URL {}", url); } } catch (Exception e) { log.error("Unable to send satus confirm URL " + url, e); } return; } securityService.proxyLogin(mqObj.getUsername()); if (mqObj.getType() == NotifyMQObject.TYPE_PAGE_UPDATE) { sendPageUpdateNodification(mqObj.getPageUid()); } else if (mqObj.getType() == NotifyMQObject.TYPE_SPACE_REMOVE) { sendSpaceRemovingNotification(mqObj.getSpace(), mqObj.getRemoveDelayHours()); } else if (mqObj.getType() == NotifyMQObject.TYPE_COMMENT_NOTIFY) { sendPageCommentsNotification(mqObj.getUsername(), mqObj.getPageUid(), mqObj.getCommentUid()); } else if (mqObj.getType() == NotifyMQObject.TYPE_EXT_LINK_BLOG) { syncExtBlog(mqObj.getSpaceUname(), mqObj.getBlogMeta(), mqObj.getSyncLimit()); } else if (mqObj.getType() == NotifyMQObject.TYPE_EXT_POST) { postBlog(mqObj.getBlogMeta(), mqObj.getId()); } else if (mqObj.getType() == NotifyMQObject.TYPE_EXT_POST_COMMENT) { postBlogComment(mqObj.getBlogMeta(), mqObj.getId()); } else if (mqObj.getType() == NotifyMQObject.TYPE_EXT_REMOVE_POST) { removeBlogPost(mqObj.getUsername(), mqObj.getBlogMeta(), mqObj.getId()); } else if (mqObj.getType() == NotifyMQObject.TYPE_SPACE_MEUN_UPDATED) { updateSpaceMenu(mqObj.getSpaceUname()); } } else { AuditLogger.error("Unexpected object in Index Counsumer " + msg); return; } } finally { securityService.proxyLogout(); } }
From source file:blueprint.sdk.google.gcm.GcmSender.java
/** * gets response code/*from w w w . j av a2 s. co m*/ * * @param http HTTP connection * @return 200: http ok, 6xx: {@link GcmResponse}, others: http error * @throws IOException */ @SuppressWarnings("IndexOfReplaceableByContains") private int getResponseCode(HttpURLConnection http) throws IOException { int result = http.getResponseCode(); if (result == HttpURLConnection.HTTP_OK) { int contentLength = http.getContentLength(); String contentType = http.getContentType(); if (0 == contentLength) { result = GcmResponse.ERR_NO_CONTENT; } else if (Validator.isEmpty(contentType)) { result = GcmResponse.ERR_NO_CONTENT_TYPE; } else if (0 > contentType.indexOf("application/json")) { result = GcmResponse.ERR_NOT_JSON; } else { result = 200; } } return result; }
From source file:com.adr.taskexecutor.ui.TaskExecutorRemote.java
@Override public void run(TaskExecutor.RunProcess ui) throws Exception { URL url;/*from ww w. j a va 2 s . c om*/ BufferedReader readerin = null; Writer writerout = null; try { // http://localhost:8084/taskexecutor/executetask?parameter=&loglevel=INFO&trace=false&stats=true&task= url = new URL(jURL.getText()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setAllowUserInteraction(false); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); String query = "¶meter=" + URLEncoder.encode(parameter, "UTF-8"); query += "&task=" + URLEncoder.encode(task, "UTF-8"); query += "&language=" + URLEncoder.encode(language, "UTF-8"); query += "&loglevel=" + URLEncoder.encode(jLoggingLevel.getSelectedItem().toString(), "UTF-8"); query += "&trace=" + URLEncoder.encode(Boolean.toString(jTrace.isSelected()), "UTF-8"); query += "&stats=" + URLEncoder.encode(Boolean.toString(jStats.isSelected()), "UTF-8"); writerout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); writerout.write("Content-Type: application/x-www- form-urlencoded,encoding=UTF-8\n"); writerout.write("Content-length: " + String.valueOf(query.length()) + "\n"); writerout.write("\n"); writerout.write(query); writerout.flush(); writerout.close(); writerout = null; int responsecode = connection.getResponseCode(); if (responsecode == HttpURLConnection.HTTP_OK) { StringBuilder text = new StringBuilder(); readerin = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String line = null; while ((line = readerin.readLine()) != null) { text.append(line); text.append(System.getProperty("line.separator")); } JSONParser jsonp = new JSONParser(); JSONObject json = (JSONObject) jsonp.parse(text.toString()); // Print lines JSONArray jsonlines = (JSONArray) json.get("lines"); for (Object l : jsonlines) { JSONObject jsonline = (JSONObject) l; Object type = jsonline.get("type"); if ("build".equals(type)) { ui.buildMessage((String) jsonline.get("text")); } else if ("run".equals(type)) { ui.runMessage((String) jsonline.get("text")); } else if ("out".equals(type)) { ui.printOut((String) jsonline.get("text")); } else if ("log".equals(type)) { ui.printLog((String) jsonline.get("text")); } else if ("success".equals(type)) { ui.successMessage(((Number) jsonline.get("time")).longValue()); } else if ("fail".equals(type)) { ui.failMessage((String) jsonline.get("text"), ((Number) jsonline.get("time")).longValue()); } else if ("exception".equals(type)) { ui.exceptionMessage((String) jsonline.get("text"), ((Number) jsonline.get("time")).longValue()); } } // Print stats ui.getStatsModel().reset(); JSONArray jsonstats = (JSONArray) json.get("stats"); if (jsonstats != null) { for (Object l : jsonstats) { JSONObject jsonstat = (JSONObject) l; ui.getStatsModel().addRow((String) jsonstat.get("task"), (String) jsonstat.get("step"), ((Number) jsonstat.get("executions")).intValue(), ((Number) jsonstat.get("records")).intValue(), ((Number) jsonstat.get("rejected")).intValue(), ((Number) jsonstat.get("totaltime")).doubleValue(), ((Number) jsonstat.get("avgtime")).doubleValue()); } } // save preferences if execution went well Configuration.getInstance().setPreference("remote.serverurl", jURL.getText()); Configuration.getInstance().setPreference("remote.logginglevel", jLoggingLevel.getSelectedItem().toString()); Configuration.getInstance().setPreference("remote.trace", Boolean.toString(jTrace.isSelected())); Configuration.getInstance().setPreference("remote.stats", Boolean.toString(jStats.isSelected())); Configuration.getInstance().flushPreferences(); // } catch (NullPointerException ex) { // } catch (ClassCastException ex) { // } catch (ParseException ex) { } else { throw new IOException(MessageFormat.format(bundle.getString("message.httperror"), Integer.toString(responsecode), connection.getResponseMessage())); } // } catch (MalformedURLException ex) { // } catch (IOException ex) { } finally { if (writerout != null) { try { writerout.close(); } catch (IOException ex) { } writerout = null; } if (readerin != null) { try { readerin.close(); } catch (IOException ex) { } readerin = null; } } }
From source file:forseti.MultipartUtility.java
/** * Completes the request and receives response from the server. * @return a list of Strings as response in case the server returned * status OK, otherwise an exception is thrown. * @throws IOException// w ww .j a va 2 s.c o m */ public InputStream connect() throws IOException { InputStream is; writer.append(LINE_FEED).flush(); writer.append("--" + boundary + "--").append(LINE_FEED); writer.close(); // checks server's status code first int status = httpConn.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { is = httpConn.getInputStream(); } else { throw new IOException("Server returned non-OK status: " + status); } return is; }
From source file:com.gliffy.restunit.http.JavaHttp.java
private HttpResponse createResponse(HttpURLConnection connection) throws IOException { HttpResponse response = new HttpResponse(); response.setStatusCode(connection.getResponseCode()); if (response.getStatusCode() == HttpURLConnection.HTTP_OK) { response.setBody(readBody(connection)); } else {//from www. ja va 2 s . c o m itsLogger.debug( "Got " + response.getStatusCode() + " and java.net will barf if we try to read the body"); } for (String header : connection.getHeaderFields().keySet()) { response.getHeaders().put(header, joinHeaderValues(connection.getHeaderFields().get(header))); } return response; }
From source file:com.ijiaban.uitls.AbstractGetNameTask.java
private void fetchIMGFromProfileSever() throws IOException, JSONException { String token = fetchToken();//from w ww . j av a 2 s .c om if (token == null) { return; } URL url2 = new URL(test + token); URL url3 = new URL(channeldetails + token); HttpURLConnection con2 = (HttpURLConnection) url2.openConnection(); int sc2 = con2.getResponseCode(); if (sc2 == HttpURLConnection.HTTP_OK) { InputStream is2 = con2.getInputStream(); String image = getImage(readResponse(is2)); Toast.makeText(mFragment.getActivity(), image, 5000).show(); is2.close(); return; } else if (sc2 == 401) { GoogleAuthUtil.invalidateToken(mFragment.getActivity(), token); onError("Server auth error, please try again.", null); return; } else { onError("Server returned the following error code: " + sc2, null); return; } }
From source file:org.eclipse.hono.service.tenant.TenantHttpEndpoint.java
private void getTenant(final RoutingContext ctx) { final String tenantId = getTenantIdFromContext(ctx); doTenantHttpRequest(ctx, tenantId, TenantConstants.TenantAction.get, status -> status == HttpURLConnection.HTTP_OK, null); }