List of usage examples for java.net HttpURLConnection getHeaderField
public String getHeaderField(int n)
From source file:org.apache.olingo.fit.tecsvc.http.AcceptHeaderAcceptCharsetHeaderITCase.java
@Test public void multipleValuesInAcceptCharsetHeader2() throws Exception { URL url = new URL(SERVICE_URI + "ESAllPrim"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "utf-8;q=0.1,utf-8;q=0.8,utf8"); connection.setRequestProperty(HttpHeader.ACCEPT, ContentType.APPLICATION_JSON.toContentTypeString()); connection.connect();//from w ww .j av a 2 s.c om assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); assertNotNull(connection.getHeaderField(HttpHeader.CONTENT_TYPE)); ContentType contentType = ContentType.parse(connection.getHeaderField(HttpHeader.CONTENT_TYPE)); assertEquals("application", contentType.getType()); assertEquals("json", contentType.getSubtype()); assertEquals(2, contentType.getParameters().size()); assertEquals("utf8", contentType.getParameter("charset")); assertEquals("minimal", contentType.getParameter("odata.metadata")); final String content = IOUtils.toString(connection.getInputStream()); assertNotNull(content); }
From source file:manchester.synbiochem.datacapture.SeekConnector.java
public URL linkFileAsset(User user, Assay assay, String description, String title, URI location) { try {/*from w w w . j a va 2 s . c om*/ MultipartFormData form = makeFileLinkForm(user, assay, location, description, title); log.info("creating linked asset with title '" + title + "' from originating location " + location); HttpURLConnection c = connect("/data_files"); try { switch (postForm(c, form)) { case CREATED: case FOUND: URL url = new URL(seek, c.getHeaderField("Location")); log.info("linked asset at " + url); return url; case SERVICE_UNAVAILABLE: throw new ServiceUnavailableException("SEEK is not available"); default: readErrorFromConnection(c, "problem in file link", "link failed with code %d: %s"); case OK: return null; } } finally { c.disconnect(); } } catch (IOException e) { throw new InternalServerErrorException("HTTP error", e); } }
From source file:manchester.synbiochem.datacapture.SeekConnector.java
public URL uploadFileAsset(User user, Assay assay, String name, String description, String title, String type, String content) {/* ww w . j a v a2 s . c om*/ try { MultipartFormData form = makeFileUploadForm(user, assay, name, description, title, type, content); log.info("creating uploaded asset with title '" + title + "' and filename " + name); HttpURLConnection c = connect("/data_files"); try { switch (postForm(c, form)) { case CREATED: case FOUND: URL url = new URL(seek, c.getHeaderField("Location")); log.info("uploaded asset at " + url); return url; case SERVICE_UNAVAILABLE: throw new ServiceUnavailableException("SEEK is not available"); default: readErrorFromConnection(c, "problem in file upload", "upload failed with code %d: %s"); case OK: return null; } } finally { c.disconnect(); } } catch (IOException e) { throw new InternalServerErrorException("HTTP error", e); } }
From source file:com.dream.library.utils.AbFileUtil.java
/** * ????./*from ww w. j a v a2 s . c om*/ * * @param url ? * @return ?? */ public static String getRealFileNameFromUrl(String url) { String name = null; try { if (AbStringUtils.isEmpty(url)) { return name; } URL mUrl = new URL(url); HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection(); mHttpURLConnection.setConnectTimeout(5 * 1000); mHttpURLConnection.setRequestMethod("GET"); mHttpURLConnection.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN"); mHttpURLConnection.setRequestProperty("Referer", url); mHttpURLConnection.setRequestProperty("Charset", "UTF-8"); mHttpURLConnection.setRequestProperty("User-Agent", ""); mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive"); mHttpURLConnection.connect(); if (mHttpURLConnection.getResponseCode() == 200) { for (int i = 0;; i++) { String mine = mHttpURLConnection.getHeaderField(i); if (mine == null) { break; } if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) { Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase()); if (m.find()) return m.group(1).replace("\"", ""); } } } } catch (Exception e) { e.printStackTrace(); AbLog.e("???"); } return name; }
From source file:org.pocketcampus.plugin.moodle.server.old.MoodleServiceImpl.java
private HttpPageReply getHttpReplyWithCookie(String url, Cookie cookie) throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/5.0"); conn.setInstanceFollowRedirects(false); conn.setRequestProperty("Cookie", cookie.cookie()); if (conn.getResponseCode() == 200) return new HttpPageReply(StringUtils.fromStream(conn.getInputStream(), "UTF-8"), null); if (conn.getResponseCode() / 100 == 3) return new HttpPageReply(null, conn.getHeaderField("Location")); return new HttpPageReply(null, null); }
From source file:URLTree.FindOptimalPath.java
public void printMap(List<Node> node, int stage, String outputFile, int threshold, String ouptputFrequencyFile, String filed3) {/*from w w w . jav a 2 s .c o m*/ Map<String, Integer> countSimilarNode = new HashMap<String, Integer>(); String nodeMatrix[][] = new String[node.size()][stage]; for (int i = 0; i < node.size(); i++) { //System.out.println(Arrays.toString(node.get(i).getNodeArr())); String arr[] = node.get(i).getNodeArr(); for (int j = 0; j < arr.length; j++) { if (j < stage) { nodeMatrix[i][j] = arr[j]; } } } List<MergeSimilarNode> similarNode = new ArrayList<MergeSimilarNode>(); Map<String, Integer> wordMap = new HashMap<String, Integer>(); for (int i = 0; i < node.size(); i++) { for (int j = 0; j < stage; j++) { if (nodeMatrix[i][j] != null) { FreqWords nodeFreq = new FreqWords(); System.out.print("[" + i + j + "]: " + nodeMatrix[i][j]); if (wordMap.containsKey(nodeMatrix[i][j] + "," + j)) { wordMap.put(nodeMatrix[i][j] + "," + j, wordMap.get(nodeMatrix[i][j] + "," + j) + 1); } else { wordMap.put(nodeMatrix[i][j] + "," + j, 1); } } } System.out.println(); } List<FreqWords> freq = new ArrayList<FreqWords>(); for (Map.Entry<String, Integer> entry : wordMap.entrySet()) { FreqWords fwords = new FreqWords(); String key = entry.getKey(); Integer value = entry.getValue(); //String nodeStr[]=key.split(","); String[] nodeStr = new String[2]; StringTokenizer st = new StringTokenizer(key, ","); int k = 0; while (st.hasMoreTokens()) { nodeStr[k] = st.nextToken(); k++; } fwords.setNode(nodeStr[0]); System.out.println("node freq: " + nodeStr[1]); if (nodeStr[1] != null) { fwords.setFreq(Integer.parseInt(nodeStr[1])); } else { System.out.println("null value at" + nodeStr[0] + ": " + nodeStr[1]); } fwords.setValue(value); freq.add(fwords); } System.out.println("Done Matrix"); //System.out.println(); PrintWriter writer = null; List<String> urlList = new ArrayList<String>(); List<FilterURL> varifiedList = new ArrayList<FilterURL>(); try { writer = new PrintWriter(outputFile, "UTF-8"); for (int i = 0; i < node.size(); i++) { String urlArr[] = new String[stage]; int flag = 0; int sum = 0; for (int j = 0; j < stage; j++) { if (nodeMatrix[i][j] != null) { for (FreqWords words : freq) { //System.out.println(); //if(words.getNode().equals("ca")) // System.out.println("words: "+words.getNode()+" i: "+i+"j: "+j+" value: "+nodeMatrix[i][j]+" word Freq: "+ words.getFreq()); if (words.getNode().equals(nodeMatrix[i][j])) { //if(words.getFreq()!=0) //{ if (words.getFreq() == j) { int count = node.get(i).getCount(); //url=url.append(nodeMatrix[i][j]).append("(").append(value+node.get(i).getCount()).append(")-"); if (threshold > words.getValue()) { flag = 1; break; } else { sum += count; urlArr[j] = nodeMatrix[i][j]; // System.out.println("i: "+i+"j: "+j+" found: "+urlArr[j]); break; //System.out.print(nodeMatrix[i][j]+"("+value+")"); } } //} } } } if (flag == 1) { flag = 0; break; } } //String urldata=StringUtils.join(urlArr,"-"); String urldata = Joiner.on("-").skipNulls().join(urlArr).trim(); //System.out.println("Mearge URL"+urldata); if (urldata.endsWith("-")) { urldata = urldata.substring(0, urldata.length() - 1); } urldata = StringUtils.stripEnd(urldata, null); // System.out.print(urldata); if (!urldata.isEmpty()) { if (urldata.contains("-")) { // writer.println(urldata+","+sum); FilterURL filter = new FilterURL(); filter.setReversedURL(urldata); filter.setCount(sum); varifiedList.add(filter); } } //System.out.println(i); // System.out.println(i); } //varifiedSequece(varifiedList,writer); for (int i = 0; i < varifiedList.size() - 1; i++) { if (varifiedList.get(i).getReversedURL().contains(varifiedList.get(i + 1).getReversedURL())) { } else { if (threshold != 0) { String nodesName[] = varifiedList.get(i).getReversedURL().split("-"); if (nodesName.length == 2) { try { String url2Domain = "http://" + nodesName[1] + "." + nodesName[0]; URL url = new URL(url2Domain); // open connection HttpURLConnection httpURLConnection = (HttpURLConnection) url .openConnection(Proxy.NO_PROXY); // stop following browser redirect httpURLConnection.setInstanceFollowRedirects(false); httpURLConnection.setConnectTimeout(15000); httpURLConnection.setReadTimeout(15000); // extract location header containing the actual destination URL String expandedURL = httpURLConnection.getHeaderField("Location"); httpURLConnection.disconnect(); if (expandedURL != null) { System.out.println("Correct: " + expandedURL); writer.println(varifiedList.get(i).getReversedURL() + "," + varifiedList.get(i).getCount()); } } catch (Exception e) { System.out.println("Incorrect: " + e); } } else { writer.println( varifiedList.get(i).getReversedURL() + "," + varifiedList.get(i).getCount()); } } else { writer.println(varifiedList.get(i).getReversedURL() + "," + varifiedList.get(i).getCount()); } } } } catch (Exception e) { e.printStackTrace(); System.out.println(e); } finally { if (writer != null) { writer.close(); // **** closing it flushes it and reclaims resources **** } } System.out.println("Write into File->" + outputFile); Path obj = new Path(); obj.finalFrequency(outputFile, ouptputFrequencyFile); // obj.preSunbrust(ouptputFrequencyFile,filed3); }
From source file:calliope.db.CouchConnection.java
/** * Get a document's revid//from w ww. j ava 2s. c o m * @param db the database name * @param docID a prepared docID * @return a string or null to indicate it isn't there */ private String getRevId(String db, String docID) throws AeseException { HttpURLConnection conn = null; try { String login = (user == null) ? "" : user + ":" + password + "@"; URL u = new URL("http://" + login + host + ":" + dbPort + "/" + db + "/" + docID); conn = (HttpURLConnection) u.openConnection(); conn.setRequestMethod("HEAD"); conn.setRequestProperty("Content-Type", MIMETypes.JSON); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.connect(); //Get Response String revid = conn.getHeaderField("ETag"); if (revid != null) revid = revid.replaceAll("\"", ""); conn.disconnect(); return revid; } catch (Exception e) { if (conn != null) conn.disconnect(); throw new AeseException(e); } }
From source file:org.onehippo.translate.TranslateWorkflowImpl.java
protected void translate(String sourceLanguage, String targetLanguage, List<String> texts) throws WorkflowException, RepositoryException { try {// ww w .j av a 2 s. c o m final String parameters = createParamters(texts, targetLanguage, sourceLanguage); if (log.isDebugEnabled()) { log.debug("request to google translate \"{}\" with parameters \"{}\"", GOOGLE_TRANSLATE_URL_V2, parameters); } URL url = new URL(GOOGLE_TRANSLATE_URL_V2); HttpURLConnection connection = null; PrintWriter out = null; Reader in = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty("X-HTTP-Method-Override", "GET"); out = new PrintWriter(connection.getOutputStream()); out.write(parameters); out.flush(); final int status = connection.getResponseCode(); if (status == 200) { String charset = getCharset(connection.getHeaderField("Content-Type")); in = new InputStreamReader(connection.getInputStream(), charset); final String response = IOUtils.toString(in); if (log.isDebugEnabled()) { log.debug("response from google translate reads \"{}\"", response); } JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("translations"); for (int i = 0; i < jsonArray.length(); i++) { String translatedText = jsonArray.getJSONObject(i).getString("translatedText"); if (log.isDebugEnabled()) { log.debug("translated \"{}\" to \"{}\"", texts.get(i), translatedText); } texts.set(i, translatedText); } } else { in = new InputStreamReader(connection.getErrorStream()); log.warn("Failed to translate field, google translate responded with status {}", status); log.warn("Google response: {}", IOUtils.toString(in)); } } finally { if (connection != null) { connection.disconnect(); } IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } catch (JSONException | IOException ex) { session.refresh(false); throw new WorkflowException("Failed to translate document", ex); } }
From source file:org.callimachusproject.test.WebResource.java
public byte[] post(String type, byte[] body, String accept) throws IOException { HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept", accept); con.setRequestProperty("Accept-Encoding", "gzip"); con.setRequestProperty("Content-Type", type); con.setDoOutput(true);//from w w w. java 2 s .c o m OutputStream req = con.getOutputStream(); try { req.write(body); } finally { req.close(); } Assert.assertEquals(con.getResponseMessage(), 200, con.getResponseCode()); InputStream in = con.getInputStream(); try { if ("gzip".equals(con.getHeaderField("Content-Encoding"))) { in = new GZIPInputStream(in); } ByteArrayOutputStream out = new ByteArrayOutputStream(); ChannelUtil.transfer(in, out); return out.toByteArray(); } finally { in.close(); } }
From source file:com.ibm.stocator.fs.swift.auth.PasswordScopeAccessProvider.java
/** * Authentication logic//from w w w . ja v a 2 s .co m * * @return Access JOSS access object * @throws IOException if failed to parse the response */ public Access passwordScopeAuth() throws IOException { InputStreamReader reader = null; BufferedReader bufReader = null; try { JSONObject user = new JSONObject(); user.put("id", mUserId); user.put("password", mPassword); JSONObject password = new JSONObject(); password.put("user", user); JSONArray methods = new JSONArray(); methods.add("password"); JSONObject identity = new JSONObject(); identity.put("methods", methods); identity.put("password", password); JSONObject project = new JSONObject(); project.put("id", mProjectId); JSONObject scope = new JSONObject(); scope.put("project", project); JSONObject auth = new JSONObject(); auth.put("identity", identity); auth.put("scope", scope); JSONObject requestBody = new JSONObject(); requestBody.put("auth", auth); HttpURLConnection connection = (HttpURLConnection) new URL(mAuthUrl).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Type", "application/json"); OutputStream output = connection.getOutputStream(); output.write(requestBody.toString().getBytes()); int status = connection.getResponseCode(); if (status != 201) { return null; } reader = new InputStreamReader(connection.getInputStream()); bufReader = new BufferedReader(reader); String res = bufReader.readLine(); JSONParser parser = new JSONParser(); JSONObject jsonResponse = (JSONObject) parser.parse(res); String token = connection.getHeaderField("X-Subject-Token"); PasswordScopeAccess access = new PasswordScopeAccess(jsonResponse, token, mPrefferedRegion); bufReader.close(); reader.close(); connection.disconnect(); return access; } catch (Exception e) { if (bufReader != null) { bufReader.close(); } if (reader != null) { reader.close(); } throw new IOException(e); } }