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.peterbaldwin.vlcremote.net.ServerConnectionTest.java
@Override protected void onPostExecute(Integer result) { switch (result) { case HttpURLConnection.HTTP_UNAUTHORIZED: Toast.makeText(context, R.string.server_unauthorized, Toast.LENGTH_SHORT).show(); break;/* www . j a va2 s. com*/ case HttpURLConnection.HTTP_FORBIDDEN: Toast.makeText(context, R.string.server_forbidden, Toast.LENGTH_SHORT).show(); break; case HttpURLConnection.HTTP_OK: Toast.makeText(context, R.string.server_ok, Toast.LENGTH_SHORT).show(); break; default: Toast.makeText(context, R.string.server_error, Toast.LENGTH_SHORT).show(); } }
From source file:com.datos.vfs.provider.http.HttpRandomAccessContent.java
@Override protected DataInputStream getDataInputStream() throws IOException { if (dis != null) { return dis; }// w w w . j a v a 2 s . c o m final GetMethod getMethod = new GetMethod(); fileObject.setupMethod(getMethod); getMethod.setRequestHeader("Range", "bytes=" + filePointer + "-"); final int status = fileSystem.getClient().executeMethod(getMethod); if (status != HttpURLConnection.HTTP_PARTIAL && status != HttpURLConnection.HTTP_OK) { throw new FileSystemException("vfs.provider.http/get-range.error", fileObject.getName(), Long.valueOf(filePointer), Integer.valueOf(status)); } mis = new HttpFileObject.HttpInputStream(getMethod); // If the range request was ignored if (status == HttpURLConnection.HTTP_OK) { final long skipped = mis.skip(filePointer); if (skipped != filePointer) { throw new FileSystemException("vfs.provider.http/get-range.error", fileObject.getName(), Long.valueOf(filePointer), Integer.valueOf(status)); } } dis = new DataInputStream(new FilterInputStream(mis) { @Override public int read() throws IOException { final int ret = super.read(); if (ret > -1) { filePointer++; } return ret; } @Override public int read(final byte[] b) throws IOException { final int ret = super.read(b); if (ret > -1) { filePointer += ret; } return ret; } @Override public int read(final byte[] b, final int off, final int len) throws IOException { final int ret = super.read(b, off, len); if (ret > -1) { filePointer += ret; } return ret; } }); return dis; }
From source file:net.joala.expression.library.net.UriStatusCodeExpressionTest.java
@Test public void get_should_work_for_HTTP_OK() throws Exception { final int expectedStatusCode = HttpURLConnection.HTTP_OK; webservice.getHttpHandler().feedResponses(statusCode(expectedStatusCode)); final int actualStatusCode = new UriStatusCodeExpression(webservice.getClientUri()).get(); assertEquals("Retrieved status code should match expected one.", expectedStatusCode, actualStatusCode); assertEquals("All fed responses should have been read.", 0, webservice.getHttpHandler().availableResponses()); }
From source file:info.jtrac.mylyn.JtracClient.java
private String doPost(String url, String message) throws Exception { PostMethod post = new PostMethod(url); post.setRequestEntity(new StringRequestEntity(message, "text/xml", "UTF-8")); String response = null;//from w w w. j av a 2s . c o m int code; try { code = httpClient.executeMethod(post); if (code != HttpURLConnection.HTTP_OK) { throw new HttpException("HTTP Response Code: " + code); } response = post.getResponseBodyAsString(); } finally { post.releaseConnection(); } return response; }
From source file:cc.vileda.sipgatesync.api.SipgateApi.java
@NonNull private static String getUrl(final String apiUrl, final String token) throws IOException { final HttpURLConnection urlConnection = getConnection(apiUrl); urlConnection.setDoInput(true);// w w w . j a va 2 s. c o m urlConnection.setRequestMethod("GET"); if (token != null) { urlConnection.setRequestProperty("Authorization", "Bearer " + token); } StringBuilder sb = new StringBuilder(); int HttpResult = urlConnection.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8")); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); return sb.toString(); } else { System.out.println(urlConnection.getResponseMessage()); } return ""; }
From source file:org.semantictools.jsonld.impl.AppspotContextPublisher.java
@Override public void publish(LdAsset asset) throws LdPublishException { String uri = asset.getURI();// w w w .j ava 2s. co m HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(SERVLET_URL); post.setHeader("CONTENT-TYPE", "multipart/form-data; boundary=xxxBOUNDARYxxx"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "xxxBOUNDARYxxx", Charset.forName("UTF-8")); try { String content = asset.loadContent(); entity.addPart(URI, new StringBody(uri)); entity.addPart(FILE_UPLOAD, new StringBody(content)); post.setEntity(entity); logger.debug("uploading... " + uri); HttpResponse response = client.execute(post); int status = response.getStatusLine().getStatusCode(); client.getConnectionManager().shutdown(); if (status != HttpURLConnection.HTTP_OK) { throw new LdPublishException(uri, null); } } catch (Exception e) { throw new LdPublishException(uri, e); } }
From source file:net.mceoin.cominghome.api.NestUtil.java
/** * Make HTTP/JSON call to Nest and set away status. * * @param access_token OAuth token to allow access to Nest * @param structure_id ID of structure with thermostat * @param away_status Either "home" or "away" * @return Equal to "Success" if successful, otherwise it contains a hint on the error. *///from w w w . j a v a 2 s . c om public static String tellNestAwayStatusCall(String access_token, String structure_id, String away_status) { String urlString = "https://developer-api.nest.com/structures/" + structure_id + "/away?auth=" + access_token; log.info("url=" + urlString); StringBuilder builder = new StringBuilder(); boolean error = false; String errorResult = ""; HttpURLConnection urlConnection = null; try { URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0"); urlConnection.setRequestMethod("PUT"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setChunkedStreamingMode(0); urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8"); String payload = "\"" + away_status + "\""; OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream()); wr.write(payload); wr.flush(); log.info(payload); boolean redirect = false; // normally, 3xx is redirect int status = urlConnection.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 // Temporary redirect || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } // System.out.println("Response Code ... " + status); if (redirect) { // get redirect url from "location" header field String newUrl = urlConnection.getHeaderField("Location"); // open the new connnection again urlConnection = (HttpURLConnection) new URL(newUrl).openConnection(); urlConnection.setRequestMethod("PUT"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setChunkedStreamingMode(0); urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8"); urlConnection.setRequestProperty("Accept", "application/json"); // System.out.println("Redirect to URL : " + newUrl); wr = new OutputStreamWriter(urlConnection.getOutputStream()); wr.write(payload); wr.flush(); } int statusCode = urlConnection.getResponseCode(); log.info("statusCode=" + statusCode); if ((statusCode == HttpURLConnection.HTTP_OK)) { error = false; } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { // bad auth error = true; errorResult = "Unauthorized"; } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) { error = true; InputStream response; response = urlConnection.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } log.info("response=" + builder.toString()); JSONObject object = new JSONObject(builder.toString()); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("error")) { // error = Internal Error on bad structure_id errorResult = object.getString("error"); log.info("errorResult=" + errorResult); } } } else { error = true; errorResult = Integer.toString(statusCode); } } catch (IOException e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("IOException: " + errorResult); } catch (Exception e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("Exception: " + errorResult); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } if (error) { return "Error: " + errorResult; } else { return "Success"; } }
From source file:com.stackify.api.common.log.LogSender.java
/** * Sends a group of log messages to Stackify * @param group The log message group//from w w w . ja v a 2 s . co m * @return The HTTP status code returned from the HTTP POST * @throws IOException */ public int send(final LogMsgGroup group) throws IOException { Preconditions.checkNotNull(group); HttpClient httpClient = new HttpClient(apiConfig); // retransmit any logs on the resend queue resendQueue.drain(httpClient, LOG_SAVE_PATH, true); // convert to json bytes byte[] jsonBytes = objectMapper.writer().writeValueAsBytes(group); // post to stackify int statusCode = HttpURLConnection.HTTP_INTERNAL_ERROR; try { httpClient.post(LOG_SAVE_PATH, jsonBytes, true); statusCode = HttpURLConnection.HTTP_OK; } catch (IOException t) { LOGGER.info("Queueing logs for retransmission due to IOException"); resendQueue.offer(jsonBytes, t); throw t; } catch (HttpException e) { statusCode = e.getStatusCode(); LOGGER.info("Queueing logs for retransmission due to HttpException", e); resendQueue.offer(jsonBytes, e); } return statusCode; }
From source file:com.example.appengine.UrlFetchServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String id = req.getParameter("id"); String text = req.getParameter("text"); if (id == null || text == null || id == "" || text == "") { req.setAttribute("error", "invalid input"); req.getRequestDispatcher("/main.jsp").forward(req, resp); return;/*from w ww. j av a 2 s. c om*/ } JSONObject jsonObj = new JSONObject().put("userId", 33).put("id", id).put("title", text).put("body", text); // [START complex] URL url = new URL("http://jsonplaceholder.typicode.com/posts/" + id); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("PUT"); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(URLEncoder.encode(jsonObj.toString(), "UTF-8")); writer.close(); int respCode = conn.getResponseCode(); // New items get NOT_FOUND on PUT if (respCode == HttpURLConnection.HTTP_OK || respCode == HttpURLConnection.HTTP_NOT_FOUND) { req.setAttribute("error", ""); StringBuffer response = new StringBuffer(); String line; BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); req.setAttribute("response", response.toString()); } else { req.setAttribute("error", conn.getResponseCode() + " " + conn.getResponseMessage()); } // [END complex] req.getRequestDispatcher("/main.jsp").forward(req, resp); }
From source file:br.com.bea.androidtools.api.proxy.AppProxy.java
@Override public List<JSONArray> request(final byte[] data) throws ConnectException { if (null == connection) throw new ConnectException("Conexo no realizada!"); try {/*from ww w . java2 s. c o m*/ if (null != data) { connection.setDoOutput(true); connection.setFixedLengthStreamingMode(data.length); output = connection.getOutputStream(); output.write(data); output.flush(); } input = connection.getInputStream(); final StringBuilder sb = new StringBuilder(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { final BufferedReader reader = new BufferedReader(new InputStreamReader(input, "utf-8"), 8); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } } return Arrays.asList(new JSONArray(sb.toString())); } catch (final Exception e) { e.printStackTrace(); } return null; }