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:rogerthat.topdesk.bizz.Util.java
public static void uploadFile(String apiUrl, String apiKey, String unid, byte[] content, String contentType, String fileName) throws IOException, ParseException { URL url = new URL(apiUrl + "/api/incident/upload/" + unid); HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST, FetchOptions.Builder.withDeadline(30)); log.info("Uploading attachment of size " + content.length / 1000 + "KB"); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addBinaryBody("filename", content, org.apache.http.entity.ContentType.create(contentType), fileName); addMultipartBodyToRequest(multipartEntityBuilder.build(), request); String authHeader = "TOKEN id=\"" + apiKey + "\""; request.addHeader(new HTTPHeader("Authorization", authHeader)); URLFetchService urlFetch = URLFetchServiceFactory.getURLFetchService(); HTTPResponse response = urlFetch.fetch(request); int responseCode = response.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { String responseContent = getContent(response); throw new TopdeskApiException("Uploading image " + fileName + " failed with response code " + responseCode + "\nContent:" + responseContent); }//from w ww. ja va 2s .c o m }
From source file:com.treasure_data.client.DefaultClientAdaptorImpl.java
private AuthenticateResult doAuthenticate(AuthenticateRequest request) throws ClientException { request.setCredentials(getConfig().getCredentials()); String jsonData = null;//w ww . j a v a 2 s. co m String message = null; int code = 0; try { conn = createConnection(); // send request String path = HttpURL.V3_USER_AUTHENTICATE; Map<String, String> header = new HashMap<String, String>(); setUserAgentHeader(header); Map<String, String> params = new HashMap<String, String>(); params.put("user", HttpConnectionImpl.e(request.getEmail())); params.put("password", HttpConnectionImpl.e(request.getPassword())); conn.doPostRequest(request, path, header, params); // receive response code code = conn.getResponseCode(); message = conn.getResponseMessage(); if (code != HttpURLConnection.HTTP_OK) { String errMessage = conn.getErrorMessage(); LOG.severe(HttpClientException.toMessage("Authentication failed", message, code)); LOG.severe(errMessage); throw new HttpClientException("Authentication failed", message + ", detail = " + errMessage, code); } // receive response body jsonData = conn.getResponseBody(); validator.validateJSONData(jsonData); } catch (IOException e) { LOG.log(Level.WARNING, "Authentication failed", e); throw new HttpClientException("Authentication failed", message, code, e); } finally { if (conn != null) { conn.disconnect(); } } // { "user":"myemailaddress","apikey":"myapikey" } // parse JSON data @SuppressWarnings("unchecked") Map<String, String> map = (Map<String, String>) JSONValue.parse(jsonData); validator.validateJavaObject(jsonData, map); //String user = map.get("user"); String apiKey = map.get("apikey"); TreasureDataCredentials credentails = new TreasureDataCredentials(apiKey); return new AuthenticateResult(credentails); }
From source file:br.eti.ranieri.opcoesweb.importacao.online.ImportadorOnlineBanif.java
/** * Baixa as cotaes de aes ou opes cujos cdigos so separados por ponto-e-vrgula. * /*from w ww. j a v a 2 s. co m*/ * @return o XML de resposta do Banif ou null, se a resposta no for HTTP 200 OK. */ String baixarCotacoes(ConfiguracaoOnline configuracao, String codigos) throws Exception { URLFetchService service = URLFetchServiceFactory.getURLFetchService(); HTTPRequest request = new HTTPRequest(new URL(BANIF_URL + codigos), HTTPMethod.GET); request.addHeader(new HTTPHeader("Cookie", "jsessionid=" + configuracao.getJsessionid())); HTTPResponse response = service.fetch(request); if (response.getResponseCode() != HttpURLConnection.HTTP_OK) { return null; } String encoding = "ISO-8859-1"; for (HTTPHeader header : response.getHeaders()) { if ("Content-Type".equalsIgnoreCase(header.getName())) { if (header.getValue() != null && header.getValue().toLowerCase().contains("CHARSET=UTF-8")) { encoding = "UTF-8"; } } } return new String(response.getContent(), encoding); }
From source file:com.edgenius.wiki.Shell.java
public static String requestSpaceThemeName(String spaceUname) { try {/*from w w w .j a v a2s. co m*/ log.info("Request shell theme for space {}", spaceUname); //reset last keyValidator value - will use new one. HttpURLConnection conn = (HttpURLConnection) new URL(getThemeRequestURL(spaceUname)).openConnection(); conn.setConnectTimeout(timeout); InputStream is = conn.getInputStream(); ByteArrayOutputStream writer = new ByteArrayOutputStream(); int len; byte[] bytes = new byte[200]; while ((len = is.read(bytes)) != -1) { writer.write(bytes, 0, len); } if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { return new String(writer.toByteArray()); } } catch (IOException e) { log.error("Unable to connect shell for theme name request", e); } catch (Throwable e) { log.error("Notify shell failure", e); } return null; }
From source file:edu.cmu.cs.quiltview.RequestPullingService.java
private void pullRequest() { String resultTxt = " " + DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis()); Log.i(LOG_TAG, "Begin pull." + resultTxt); getLocation();/*w w w. jav a 2 s . c o m*/ double latitude, longitude; if (mLocation != null) { Log.i(LOG_TAG, "Real Location"); latitude = mLocation.getLatitude(); longitude = mLocation.getLongitude(); } else { //TODO test real location /* * As we usually develop and demo indoor, the GPS location is not always * available. For the convenience of development, we use theses fixed fake * location. This is somewhere on Carnegie Mellon University campus * Wenlu Hu, April 2014 */ Log.i(LOG_TAG, "Fake Location"); latitude = 40.443469; //40.44416720; longitude = -79.943862; //-79.94336060; } Log.i(LOG_TAG, "Location: " + latitude + ", " + longitude); HttpURLConnection urlConnection = null; try { URL url = new URL(Const.quiltview_server_addr + "/latest/" + "?user_id=" + mSerialNumber + "&lat=" + latitude + "&lng=" + longitude); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setRequestProperty("Content-Type", "application/json"); if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = urlConnection.getInputStream(); int responseLen = urlConnection.getContentLength(); Log.i(LOG_TAG, "Response Len = " + responseLen); //Read the json file byte[] jsonBuffer = new byte[responseLen]; Log.i(LOG_TAG, "Response Len = " + is.read(jsonBuffer)); String jsonString = new String(jsonBuffer, "UTF-8"); Log.i(LOG_TAG, "Got response: " + jsonString); try { JSONObject obj = (JSONObject) JSONValue.parse(jsonString); String query = obj.get("content").toString(); int queryID = Integer.parseInt(obj.get("query_id").toString()); int userID = Integer.parseInt(obj.get("user_id").toString()); String imagePath = obj.get("image").toString(); Log.i(LOG_TAG, userID + ", " + queryID + ": " + query + "&" + imagePath); imagePath = saveImageToLocal(imagePath); recordForQuery(query, queryID, userID, imagePath); } catch (NullPointerException ex) { Log.i(LOG_TAG, "No valid query"); } } else { Log.e(LOG_TAG, "Response " + urlConnection.getResponseCode() + ":" + urlConnection.getResponseMessage()); } } catch (MalformedURLException ex) { Log.e(LOG_TAG, "", ex); } catch (IOException ex) { Log.e(LOG_TAG, "", ex); } finally { if (urlConnection != null) urlConnection.disconnect(); } }
From source file:com.google.enterprise.adaptor.experimental.Sim.java
private void processMultipartPost(HttpExchange ex) throws IOException { InputStream inStream = ex.getRequestBody(); String encoding = ex.getRequestHeaders().getFirst("Content-encoding"); if (null != encoding && "gzip".equals(encoding.toLowerCase())) { inStream = new GZIPInputStream(inStream); }/*w w w. ja v a 2 s. c om*/ String lens = ex.getRequestHeaders().getFirst("Content-Length"); long len = (null != lens) ? Long.parseLong(lens) : 0; String ct = ex.getRequestHeaders().getFirst("Content-Type"); try { String xml = extractFeedFromMultipartPost(inStream, len, ct); processXml(xml); respond(ex, HttpURLConnection.HTTP_OK, "text/plain", "Success".getBytes(UTF8)); } catch (NoXmlFound nox) { log.warning("failed to find xml"); respond(ex, HttpURLConnection.HTTP_BAD_REQUEST, "text/plain", "xml beginning not found".getBytes(UTF8)); } catch (SAXException saxe) { log.warning("sax error: " + saxe.getMessage()); respond(ex, HttpURLConnection.HTTP_BAD_REQUEST, "text/plain", "sax not liking the xml".getBytes(UTF8)); } catch (ParserConfigurationException confige) { log.warning("parser error: " + confige.getMessage()); respond(ex, HttpURLConnection.HTTP_BAD_REQUEST, "text/plain", "parser error".getBytes(UTF8)); } catch (BadFeed bad) { log.warning("error in feed: " + bad.getMessage()); respond(ex, HttpURLConnection.HTTP_BAD_REQUEST, "text/plain", bad.getMessage().getBytes(UTF8)); } }
From source file:com.ssn.listener.SSNHiveAlbumSelectionListner.java
private void getAlbumMedia(String accessToken, int pageCount, SSNAlbum album) { try {//www.ja va 2s. com String urlString = SSNConstants.SSN_WEB_HOST + "api/albums/view/%s/page:%s.json"; URL url = new URL(String.format(urlString, album.getId(), pageCount)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String input = "access_token=%s"; input = String.format(input, URLEncoder.encode(accessToken, "UTF-8")); OutputStream os = conn.getOutputStream(); Writer writer = new OutputStreamWriter(os, "UTF-8"); writer.write(input); writer.close(); os.close(); int status = conn.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; StringBuilder response = new StringBuilder(); while ((output = br.readLine()) != null) { response.append(output); } ObjectMapper mapper = new ObjectMapper(); Map<String, Object> outputJSON = mapper.readValue(response.toString(), Map.class); boolean success = (Boolean) outputJSON.get("success"); if (success) { List<Map<String, Object>> mediaFileListJSON = (List<Map<String, Object>>) outputJSON .get("MediaFile"); ssnHiveAlbumAllMedia = new HashMap<String, SSNAlbumMedia>(); if (mediaFileListJSON.size() > 0) { for (Map<String, Object> mediaFileJSON : mediaFileListJSON) { SSNAlbumMedia ssnAlbumMedia = mapper.readValue(mapper.writeValueAsString(mediaFileJSON), SSNAlbumMedia.class); String name = ""; String[] videoSupported = SSNConstants.SSN_VIDEO_FORMAT_SUPPORTED; final List<String> videoSupportedList = Arrays.asList(videoSupported); String fileType = ssnAlbumMedia.getFile_type() .substring(ssnAlbumMedia.getFile_type().lastIndexOf("/") + 1, ssnAlbumMedia.getFile_type().length()) .toUpperCase(); if (videoSupportedList.contains(fileType)) { name = ssnAlbumMedia.getFile_name(); } else { name = ssnAlbumMedia.getThumbnail().substring( ssnAlbumMedia.getThumbnail().lastIndexOf("/") + 1, ssnAlbumMedia.getThumbnail().length()); } File mediaFile = new File( SSNHelper.getSsnTempDirPath() + album.getName() + File.separator + name); ssnHiveAlbumAllMedia.put(name, ssnAlbumMedia); int lastModificationComparision = -1; if (mediaFile.exists()) { String mediaFileModifiedDate = SSNDao.getSSNMetaData(mediaFile.getAbsolutePath()) .getModiFied(); String ssnMediaModifiedDate = ssnAlbumMedia.getModified(); lastModificationComparision = compareDates(mediaFileModifiedDate, ssnMediaModifiedDate); } if ((!mediaFile.exists() && !ssnAlbumMedia.isIs_deleted()) || (lastModificationComparision < 0)) { if (ssnAlbumMedia.getFile_url() != null && !ssnAlbumMedia.getFile_url().isEmpty() && !ssnAlbumMedia.getFile_url().equalsIgnoreCase("false")) { try { URL imageUrl = null; if (videoSupportedList.contains(fileType)) { imageUrl = new URL(ssnAlbumMedia.getFile_url().replaceAll(" ", "%20")); } else { imageUrl = new URL(ssnAlbumMedia.getThumbnail().replaceAll(" ", "%20")); } FileUtils.copyURLToFile(imageUrl, mediaFile); } catch (IOException e) { logger.error(e); } } } } } Map<String, Object> pagingJSON = (Map<String, Object>) outputJSON.get("paging"); if (pagingJSON != null) { boolean hasNextPage = Boolean.parseBoolean(pagingJSON.get("nextPage") + ""); if (hasNextPage) { getAlbumMedia(accessToken, ++pageCount, album); } } } } } catch (EOFException e) { logger.error(e); SSNMessageDialogBox dialogBox = new SSNMessageDialogBox(); dialogBox.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Message", "", "No Response from server."); } catch (Exception ee) { logger.error(ee); } }
From source file:com.polyvi.xface.extension.advancedfiletransfer.FileUploader.java
/** * ??????id?/* w w w.j a va 2s .c o m*/ * * @return true:??false:? */ private boolean handleShake() { HttpURLConnection httpConnection = null; DataInputStream dataInputStream = null; String souceid = mFileTransferRecorder.getSourceId(mFilePath, "" + mUploadFileSize); try { httpConnection = getHttpConnection(mServer); // ? httpConnection.setRequestProperty("Charset", "UTF-8"); httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpConnection.setRequestProperty("ACTIONNAME", ACTION_NAME_HAND); httpConnection.setRequestProperty("RESOURCEID", souceid); httpConnection.setRequestProperty("FILENAME", getUploadFileName()); httpConnection.setRequestProperty("FILESIZE", "" + mUploadFileSize); if (HttpURLConnection.HTTP_OK == httpConnection.getResponseCode()) { // ????? RESOURCEID=?;BFFORE=? dataInputStream = new DataInputStream(httpConnection.getInputStream()); // ???response? handleResponse(dataInputStream.readLine()); // souceid? setSourceId(souceid); } else { onError(INVALID_URL_ERR); } } catch (Exception e) { onError(INVALID_URL_ERR); e.printStackTrace(); return false; } finally { if (null != httpConnection) { httpConnection.disconnect(); httpConnection = null; } // ?? try { if (null != dataInputStream) { dataInputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return true; }