List of usage examples for java.net HttpURLConnection getURL
public URL getURL()
From source file:com.sap.wec.adtreco.be.ODataClientService.java
private HttpStatusCodes checkStatus(final HttpURLConnection connection) throws IOException { final HttpStatusCodes httpStatusCode = HttpStatusCodes.fromStatusCode(connection.getResponseCode()); if (400 <= httpStatusCode.getStatusCode() && httpStatusCode.getStatusCode() <= 599) { final String msg = "Http Connection failed with status " + httpStatusCode.getStatusCode() + " " + httpStatusCode.toString() + ".\n\tRequest URL was: '" + connection.getURL().toString() + "'."; throw new RuntimeException(msg); }/*ww w . j a v a2 s. c o m*/ return httpStatusCode; }
From source file:com.amastigote.xdu.query.module.EduSystem.java
private @Nullable JSONObject gradesQuery() throws IOException, JSONException { if (!checkIsLogin(ID)) { return null; }//from ww w. j a v a 2s. co m URL url = new URL(SYS_HOST + GRADE_QUERY_SUFFIX); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestProperty("Cookie", "JSESSIONID=" + SYS_JSESSIONID); httpURLConnection.connect(); Document document = Jsoup.parse(httpURLConnection.getInputStream(), "gb2312", httpURLConnection.getURL().toString()); document = Jsoup.parse(document.toString().replaceAll(" ", "")); JSONObject jsonObject = new JSONObject(); Elements elements_content = document.select("td[class=pageAlign]"); Elements elements_titles = document.select("b"); for (int i = 0; i < elements_titles.size(); i++) { JSONObject jsonObject_semester = new JSONObject(); String semester_key = elements_titles.get(i).text().trim(); Element table_for_this_semester = elements_content.get(i); Elements elements_rows = table_for_this_semester.select("td[align=center]"); for (int j = 0; j < elements_rows.size() / 7; j++) { JSONObject jsonObject_course = new JSONObject(); String course_key = elements_rows.get(j * 7 + 2).text().trim(); jsonObject_course.put(GradeKey.ID, elements_rows.get(j * 7).text().trim()); jsonObject_course.put(GradeKey.CREDIT, elements_rows.get(j * 7 + 4).text().trim()); jsonObject_course.put(GradeKey.ATTR, elements_rows.get(j * 7 + 5).text().trim()); jsonObject_course.put(GradeKey.GRADE, elements_rows.get(j * 7 + 6).text().trim()); jsonObject_semester.put(course_key, jsonObject_course); } jsonObject.put(semester_key, jsonObject_semester); } return jsonObject; }
From source file:org.holistic.ws_proxy.WSProxyHelper.java
private void doPost(HttpServletRequest req, HttpServletResponse resp) throws Exception { HttpURLConnection m_objURLConnection = null; m_objURLConnection = openurl(get_request(req)); // resp.setStatus(m_objURLConnection.getResponseCode()); m_objURLConnection.setDoOutput(true); m_objURLConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded"); set_headers2urlconn(req, m_objURLConnection); m_objURLConnection.setRequestProperty("host", m_objURLConnection.getURL().getHost() + ":" + m_objURLConnection.getURL().getPort()); PrintWriter m_objOutput = new PrintWriter(m_objURLConnection.getOutputStream()); m_objOutput.print(get_postdata(req)); m_objOutput.close();// www. java2s. c om resp.setStatus(m_objURLConnection.getResponseCode()); if (m_objURLConnection.getContentType() != null) resp.setContentType(m_objURLConnection.getContentType()); get_endpointstream(resp, m_objURLConnection); }
From source file:it.jnrpe.plugin.CheckHttp.java
/** * Apply the logic to check for url redirects. * //from w w w .ja v a 2 s . c o m * @param url * - The server URL * @param method * - The HTTP method * @param timeout * - The timeout * @param props * - * @param postData * - * @param redirect * - * @param ignoreBody * - * @param metrics * - This list will be filled with the gathered metrics * @return String * @throws Exception * - */ private String checkRedirectResponse(final URL url, final String method, final Integer timeout, final Properties props, final String postData, final String redirect, final boolean ignoreBody, final List<Metric> metrics) throws Exception { // @todo handle sticky/port and follow param options String response = null; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(method); HttpUtils.setRequestProperties(props, conn, timeout); String initialUrl = String.valueOf(conn.getURL()); String redirectedUrl = null; if ("POST".equals(method)) { HttpUtils.sendPostData(conn, postData); } response = HttpUtils.parseHttpResponse(conn, false, ignoreBody); redirectedUrl = String.valueOf(conn.getURL()); if (!redirectedUrl.equals(initialUrl)) { Metric metric = new Metric("onredirect", "", new BigDecimal(1), null, null); metrics.add(metric); } return response; }
From source file:com.amastigote.xdu.query.module.EduSystem.java
@Override public boolean checkIsLogin(String username) throws IOException { URL url = new URL(SYS_HOST + SYS_SUFFIX); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setInstanceFollowRedirects(false); httpURLConnection.setRequestProperty("Cookie", "JSESSIONID=" + SYS_JSESSIONID); httpURLConnection.connect();// ww w . j a v a2s . c o m Document document = Jsoup.parse(httpURLConnection.getInputStream(), "gb2312", httpURLConnection.getURL().toString()); if (document.select("title").size() == 0) { return false; } else if (document.select("title").get(0).text().equals("?")) { ID = username; return true; } return false; }
From source file:org.jboss.pnc.termdbuilddriver.transfer.TermdFileTranser.java
public void uploadScript(String script, Path remoteFilePath) throws TransferException { logger.debug("Uploading build script to remote path {}, build script {}", remoteFilePath, script); String scriptPath = UPLOAD_PATH + remoteFilePath.toAbsolutePath().toString(); logger.debug("Resolving script path {} to base uri {}", scriptPath, baseServerUri); URI uploadUri = baseServerUri.resolve(scriptPath); try {// w w w.j av a2 s .c o m HttpURLConnection connection = (HttpURLConnection) uploadUri.toURL().openConnection(); connection.setRequestMethod("PUT"); connection.setDoOutput(true); connection.setDoInput(true); byte[] fileContent = script.getBytes(); connection.setRequestProperty("Content-Length", "" + Integer.toString(fileContent.length)); try (OutputStream outputStream = connection.getOutputStream()) { outputStream.write(fileContent); } if (200 != connection.getResponseCode()) { throw new TransferException("Could not upload script to Build Agent at url " + connection.getURL() + " - Returned status code " + connection.getResponseCode()); } logger.debug("Uploaded successfully"); } catch (IOException e) { throw new TransferException("Could not upload build script: " + uploadUri.toString(), e); } }
From source file:com.amastigote.xdu.query.module.EduSystem.java
private @Nullable JSONObject lessonsQuery() throws IOException, JSONException { if (!checkIsLogin(ID)) return null; URL url = new URL(SYS_HOST + "xkAction.do?actionType=6"); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestProperty("Cookie", "JSESSIONID=" + SYS_JSESSIONID); httpURLConnection.connect();//from w w w . j a v a2 s .c o m Document document = Jsoup.parse(httpURLConnection.getInputStream(), "gb2312", httpURLConnection.getURL().toString()); document = Jsoup.parse(document.toString().replaceAll(" ", "")); Elements lessons = document.select("table[class=titleTop2]"); Element lessonsElement = lessons.get(1); Elements lessonsInfo = lessonsElement.select("tr[onmouseout=this.className='even';]"); int lessons_quantity = lessonsInfo.size(); JSONArray jsonArray = new JSONArray(); for (int i = 0; i < lessons_quantity;) { Element lessonInfo = lessonsInfo.get(i); Elements lessonDetails = lessonInfo.select("td"); // if (lessonDetails.get(14).text().equals("")) { i++; continue; } JSONObject JLessonObject = new JSONObject(); JLessonObject.put(CourseKey.ID, lessonDetails.get(1).text()); JLessonObject.put(CourseKey.NAME, lessonDetails.get(2).text()); JLessonObject.put(CourseKey.CREDIT, lessonDetails.get(4).text()); JLessonObject.put(CourseKey.LENGTH, lessonDetails.get(5).text()); JLessonObject.put(CourseKey.ATTR, lessonDetails.get(6).text()); JLessonObject.put(CourseKey.EXAM_TYPE, lessonDetails.get(7).text()); JLessonObject.put(CourseKey.TEACHER, lessonDetails.get(8).text()); JSONArray JLessonTimeAndPosArray = new JSONArray(); JSONObject JLessonTimeAndPos = new JSONObject(); JLessonTimeAndPos.put(CourseKey.WEEK, lessonDetails.get(12).text()); JLessonTimeAndPos.put(CourseKey.WEEK_DAY, lessonDetails.get(13).text()); JLessonTimeAndPos.put(CourseKey.SECTION_TIME, lessonDetails.get(14).text()); JLessonTimeAndPos.put(CourseKey.SECTION_LENGTH, lessonDetails.get(15).text()); JLessonTimeAndPos.put(CourseKey.CAMPUS, lessonDetails.get(16).text()); JLessonTimeAndPos.put(CourseKey.BUILDING, lessonDetails.get(17).text()); JLessonTimeAndPos.put(CourseKey.CLASSROOM, lessonDetails.get(18).text()); JLessonTimeAndPosArray.put(JLessonTimeAndPos); i++; //??Array int row_span; //row_span?1 if ("".equals(lessonInfo.select("td").get(0).attr("rowspan"))) { row_span = 1; } else { row_span = Integer.parseInt(lessonInfo.select("td").get(0).attr("rowspan")); } //row_span?1?? for (int j = 0; j < row_span - 1; j++, i++) { Elements EExtraTimeAndPos = lessonsInfo.get(i).select("td"); JSONObject JExtraLessonTimeAndPos = new JSONObject(); JExtraLessonTimeAndPos.put(CourseKey.WEEK, EExtraTimeAndPos.get(0).text()); JExtraLessonTimeAndPos.put(CourseKey.WEEK_DAY, EExtraTimeAndPos.get(1).text()); JExtraLessonTimeAndPos.put(CourseKey.SECTION_TIME, EExtraTimeAndPos.get(2).text()); JExtraLessonTimeAndPos.put(CourseKey.SECTION_LENGTH, EExtraTimeAndPos.get(3).text()); JExtraLessonTimeAndPos.put(CourseKey.CAMPUS, EExtraTimeAndPos.get(4).text()); JExtraLessonTimeAndPos.put(CourseKey.BUILDING, EExtraTimeAndPos.get(5).text()); JExtraLessonTimeAndPos.put(CourseKey.CLASSROOM, EExtraTimeAndPos.get(6).text()); JLessonTimeAndPosArray.put(JExtraLessonTimeAndPos); } JLessonObject.put(CourseKey.TIME_AND_LOCATION_DERAIL, JLessonTimeAndPosArray); jsonArray.put(JLessonObject); } return new JSONObject().put("ARRAY", jsonArray); }
From source file:com.microsoft.azure.storage.core.Utility.java
/** * Logs the HttpURLConnection request. If an exception is encountered, logs nothing. * //from www.j ava2 s . c o m * @param conn * The HttpURLConnection to serialize. * @param opContext * The operation context which provides the logger. */ public static void logHttpRequest(HttpURLConnection conn, OperationContext opContext) throws IOException { if (Logger.shouldLog(opContext)) { try { StringBuilder bld = new StringBuilder(); bld.append(conn.getRequestMethod()); bld.append(" "); bld.append(conn.getURL()); bld.append("\n"); // The Authorization header will not appear due to a security feature in HttpURLConnection for (Map.Entry<String, List<String>> header : conn.getRequestProperties().entrySet()) { if (header.getKey() != null) { bld.append(header.getKey()); bld.append(": "); } for (int i = 0; i < header.getValue().size(); i++) { bld.append(header.getValue().get(i)); if (i < header.getValue().size() - 1) { bld.append(","); } } bld.append('\n'); } Logger.trace(opContext, bld.toString()); } catch (Exception e) { // Do nothing } } }
From source file:org.apache.nifi.minifi.c2.provider.nifi.rest.NiFiRestConfigurationProvider.java
@Override public Configuration getConfiguration(String contentType, Integer version, Map<String, List<String>> parameters) throws ConfigurationProviderException { if (!CONTENT_TYPE.equals(contentType)) { throw new ConfigurationProviderException( "Unsupported content type: " + contentType + " supported value is " + CONTENT_TYPE); }//from w ww.j a v a 2 s.c o m String filename = templateNamePattern; for (Map.Entry<String, List<String>> entry : parameters.entrySet()) { if (entry.getValue().size() != 1) { throw new InvalidParameterException( "Multiple values for same parameter not supported in this provider."); } filename = filename.replaceAll(Pattern.quote("${" + entry.getKey() + "}"), entry.getValue().get(0)); } int index = filename.indexOf("${"); while (index != -1) { int endIndex = filename.indexOf("}", index); if (endIndex == -1) { break; } String variable = filename.substring(index + 2, endIndex); if (!"version".equals(variable)) { throw new InvalidParameterException("Found unsubstituted parameter " + variable); } index = endIndex + 1; } String id = null; if (version == null) { String filenamePattern = Arrays.stream(filename.split(Pattern.quote("${version}"), -1)) .map(Pattern::quote).collect(Collectors.joining("([0-9+])")); Pair<String, Integer> maxIdAndVersion = getMaxIdAndVersion(filenamePattern); id = maxIdAndVersion.getFirst(); version = maxIdAndVersion.getSecond(); } filename = filename.replaceAll(Pattern.quote("${version}"), Integer.toString(version)); WriteableConfiguration configuration = configurationCache.getCacheFileInfo(contentType, parameters) .getConfiguration(version); if (configuration.exists()) { if (logger.isDebugEnabled()) { logger.debug( "Configuration " + configuration + " exists and can be served from configurationCache."); } } else { if (logger.isDebugEnabled()) { logger.debug("Configuration " + configuration + " doesn't exist, will need to download and convert template."); } if (id == null) { try { String tmpFilename = templateNamePattern; for (Map.Entry<String, List<String>> entry : parameters.entrySet()) { if (entry.getValue().size() != 1) { throw new InvalidParameterException( "Multiple values for same parameter not supported in this provider."); } tmpFilename = tmpFilename.replaceAll(Pattern.quote("${" + entry.getKey() + "}"), entry.getValue().get(0)); } Pair<Stream<Pair<String, String>>, Closeable> streamCloseablePair = getIdAndFilenameStream(); try { String finalFilename = filename; id = streamCloseablePair.getFirst().filter(p -> finalFilename.equals(p.getSecond())) .map(Pair::getFirst).findFirst().orElseThrow(() -> new InvalidParameterException( "Unable to find template named " + finalFilename)); } finally { streamCloseablePair.getSecond().close(); } } catch (IOException | TemplatesIteratorException e) { throw new ConfigurationProviderException("Unable to retrieve template list", e); } } HttpURLConnection urlConnection = httpConnector.get("/templates/" + id + "/download"); try (InputStream inputStream = urlConnection.getInputStream()) { ConfigSchema configSchema = ConfigMain.transformTemplateToSchema(inputStream); SchemaSaver.saveConfigSchema(configSchema, configuration.getOutputStream()); } catch (IOException e) { throw new ConfigurationProviderException( "Unable to download template from url " + urlConnection.getURL(), e); } catch (JAXBException e) { throw new ConfigurationProviderException("Unable to convert template to yaml", e); } finally { urlConnection.disconnect(); } } return configuration; }
From source file:cm.aptoide.pt.util.NetworkUtils.java
public int checkServerConnection(final String string, final String username, final String password) { try {//from www.ja v a 2s . c o m HttpURLConnection client = (HttpURLConnection) new URL(string + "info.xml").openConnection(); if (username != null && password != null) { String basicAuth = "Basic " + new String(Base64.encode((username + ":" + password).getBytes(), Base64.NO_WRAP)); client.setRequestProperty("Authorization", basicAuth); } client.setConnectTimeout(TIME_OUT); client.setReadTimeout(TIME_OUT); if (ApplicationAptoide.DEBUG_MODE) Log.i("Aptoide-NetworkUtils-checkServerConnection", "Checking on: " + client.getURL().toString()); if (client.getContentType().equals("application/xml")) { return 0; } else { return client.getResponseCode(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return -1; }