List of usage examples for java.net HttpURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:io.druid.server.initialization.JettyTest.java
@Test public void testGzipCompression() throws Exception { final URL url = new URL("http://localhost:" + port + "/default"); final HttpURLConnection get = (HttpURLConnection) url.openConnection(); get.setRequestProperty("Accept-Encoding", "gzip"); Assert.assertEquals("gzip", get.getContentEncoding()); final HttpURLConnection post = (HttpURLConnection) url.openConnection(); post.setRequestProperty("Accept-Encoding", "gzip"); post.setRequestMethod("POST"); Assert.assertEquals("gzip", post.getContentEncoding()); final HttpURLConnection getNoGzip = (HttpURLConnection) url.openConnection(); Assert.assertNotEquals("gzip", getNoGzip.getContentEncoding()); final HttpURLConnection postNoGzip = (HttpURLConnection) url.openConnection(); postNoGzip.setRequestMethod("POST"); Assert.assertNotEquals("gzip", postNoGzip.getContentEncoding()); }
From source file:com.zzl.zl_app.cache.Utility.java
public static String uploadFile(File file, String RequestURL, String fileName) { Tools.log("IO", "RequestURL:" + RequestURL); String result = null;//from w w w . j a v a 2 s .c o m String BOUNDARY = UUID.randomUUID().toString(); // ?? String PREFIX = "--", LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; // try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(Utility.SET_SOCKET_TIMEOUT); conn.setConnectTimeout(Utility.SET_CONNECTION_TIMEOUT); conn.setDoInput(true); // ?? conn.setDoOutput(true); // ?? conn.setUseCaches(false); // ?? conn.setRequestMethod("POST"); // ? conn.setRequestProperty("Charset", CHARSET); // ? conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if (file != null) { /** * ? */ DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * ?? name???key ?key ?? * filename?????? :abc.png */ sb.append("Content-Disposition: form-data; name=\"voice\"; filename=\"" + file.getName() + "\"" + LINE_END); sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); Tools.log("FileSize", "file:" + file.length()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { dos.write(bytes, 0, len); Tools.log("FileSize", "size:" + len); } dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes(); dos.write(end_data); dos.flush(); dos.close(); is.close(); /** * ??? 200=? ????? */ int res = conn.getResponseCode(); Tools.log("IO", "ResponseCode:" + res); if (res == 200) { InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }
From source file:eu.falcon.fusion.ScheduledFusionTask.java
@Scheduled(fixedRate = 50000) public void reportCurrentTime() { System.out.println("The time is now " + dateFormat.format(new Date())); InputStream inputStream;/*w w w .ja v a 2s . c o m*/ String jsonldToSaveToMongoAndFuseki = ""; //doo rest call try { URL url = new URL("http://localhost:8083"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/ld+json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); jsonldToSaveToMongoAndFuseki += output; } conn.disconnect(); inputStream = new ByteArrayInputStream(jsonldToSaveToMongoAndFuseki.getBytes(StandardCharsets.UTF_8)); //inputStream = new FileInputStream("/home/eleni/NetBeansProjects/falcon-data-management/fusion/src/main/resources/sensorData.json"); String serviceURI = "http://localhost:3030/ds/data"; //DatasetAccessorFactory factory = null; DatasetAccessor accessor; accessor = DatasetAccessorFactory.createHTTP(serviceURI); Model m = ModelFactory.createDefaultModel(); String base = "http://test-projects.com/"; m.read(inputStream, base, "JSON-LD"); //accessor.putModel(m); accessor.add(m); inputStream.close(); } catch (IOException ex) { Logger.getLogger(FusionApplication.class.getName()).log(Level.SEVERE, null, ex); } DBObject dbObject = (DBObject) JSON.parse(jsonldToSaveToMongoAndFuseki); mongoTemplate.insert(dbObject, "sensorMeasurement"); }
From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java
public static boolean logout(String server_url, String tim_access_token) { if (isEmpty(server_url)) { Logd(TAG, "logout failed : no server url"); return false; }/* w w w.j a va2 s . c o m*/ // get revoke_logout endpoint String revoke_logout_endpoint = getEndpointFromConfigOidc("revoke_logout_endpoint", server_url); if (isEmpty(revoke_logout_endpoint)) { Logd(TAG, "logout : could not get revoke_logout_endpoint on server : " + server_url); return false; } // set up connection HttpURLConnection huc = getHUC(revoke_logout_endpoint); huc.setInstanceFollowRedirects(false); huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); huc.setDoOutput(true); huc.setChunkedStreamingMode(0); // prepare parameters List<NameValuePair> nameValuePairs = null; if (tim_access_token != null && tim_access_token.length() > 0) { nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("tat", tim_access_token)); } try { // write parameters to http connection if (nameValuePairs != null) { OutputStream os = huc.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); // get URL encoded string from list of key value pairs String postParam = getQuery(nameValuePairs); Logd("Logout", "url: " + revoke_logout_endpoint); Logd("Logout", "POST: " + postParam); writer.write(postParam); writer.flush(); writer.close(); os.close(); } // try to connect huc.connect(); // connection status int responseCode = huc.getResponseCode(); Logd(TAG, "Logout response: " + responseCode); // if 200 - OK if (responseCode == 200) { return true; } huc.disconnect(); } catch (Exception e) { e.printStackTrace(); } return false; }
From source file:com.cpjd.roblu.bluealliance.BLUE.java
/** * Makes an API call to The Blue Alliance. * /*from w w w . j a v a2 s . c om*/ * @param apiReq The REST endpoint to make a request to. * @return The parsed JSON data. */ public static Object api(String apiReq) throws BLUEApiException { if (!isInitialized()) throw new BLUEApiException("BLUE was not initialized.", null); String endpoint = API_BASE + apiReq; URL endpointUrl; try { endpointUrl = new URL(endpoint); } catch (MalformedURLException e) { throw new BLUEApiException("Malformed API request.", e); } HttpURLConnection conn; try { conn = (HttpURLConnection) endpointUrl.openConnection(); } catch (IOException e) { throw new BLUEApiException("Could not open connection.", e); } try { conn.setRequestMethod("GET"); } catch (ProtocolException e) { throw new BLUEApiException("Could not set the request type.", e); } conn.setRequestProperty("X-TBA-App-Id", X_TBA_APP_ID); conn.setUseCaches(false); InputStream is; BufferedReader reader; try { is = conn.getInputStream(); reader = new BufferedReader(new InputStreamReader(is)); } catch (IOException e) { throw new BLUEApiException("Fatal! No internet!", e); } String jsonString = ""; String respLine = ""; try { while ((respLine = reader.readLine()) != null) { jsonString += respLine; } reader.close(); } catch (IOException e) { throw new BLUEApiException("Error reading the response.", e); } Object obj; try { obj = parser.parse(jsonString); } catch (ParseException e) { throw new BLUEApiException("Malformed response received.", e); } return obj; }
From source file:MainFrame.CheckConnection.java
private boolean isOnline() throws MalformedURLException, IOException, Exception { String url = "http://www.itstepdeskview.hol.es"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", "Mozilla/5.0"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "apideskviewer.checkStatus={}"; // Send post request con.setDoOutput(true);//from w w w .ja v a 2 s.co m DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); // System.out.println("\nSending 'POST' request to URL : " + url); // System.out.println("Post parameters : " + urlParameters); // System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); JSONParser parser = new JSONParser(); Object parsedResponse = parser.parse(in); JSONObject jsonParsedResponse = (JSONObject) parsedResponse; String s = (String) jsonParsedResponse.get("response"); if (s.equals("online")) { return true; } else { return false; } }
From source file:org.piraso.replacer.spring.remoting.PirasoSimpleHttpInvokerRequestExecutor.java
protected void prepareConnection(HttpURLConnection con, int contentLength) throws IOException { super.prepareConnection(con, contentLength); if (context.isMonitored() && context.getEntryPoint() != null) { con.setRequestProperty(REMOTE_ADDRESS_HEADER, context.getEntryPoint().getRemoteAddr()); con.setRequestProperty(REQUEST_ID_HEADER, String.valueOf(context.getRequestId())); con.setRequestProperty(METHOD_NAME_HEADER, String.valueOf( context.getProperty(PirasoSimpleHttpInvokerRequestExecutor.class, METHOD_NAME_HEADER))); }//from w w w.j a va 2s .c o m }
From source file:net.ae97.pokebot.extensions.scrolls.PlayerCommand.java
@Override public void runEvent(CommandEvent event) { String name = event.getArgs().length > 0 ? event.getArgs()[0] : event.getUser().getNick(); try {//from w ww .jav a 2s.co m URL playerURL = new URL(url.replace("{name}", name)); List<String> lines = new LinkedList<>(); HttpURLConnection conn = (HttpURLConnection) playerURL.openConnection(); conn.setRequestProperty("User-Agent", "PokeBot - " + PokeBot.VERSION); conn.connect(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { lines.add(line); } } JsonParser parser = new JsonParser(); JsonElement element = parser.parse(StringUtils.join(lines, "\n")); JsonObject obj = element.getAsJsonObject(); String result = obj.get("msg").getAsString(); if (!result.equalsIgnoreCase("success")) { event.respond("No data could be retrieved for " + name); return; } JsonObject dataObject = obj.get("data").getAsJsonObject(); StringBuilder builder = new StringBuilder(); if (event.getUser().getNick().equalsIgnoreCase(dataObject.get("name").getAsString())) { builder.append("Your"); } else { builder.append(dataObject.get("name").getAsString()).append("'s"); } builder.append(" stats - "); builder.append("Rating: ").append(dataObject.get("rating").getAsInt()).append(" - "); builder.append("Rank: ").append(dataObject.get("rank").getAsInt()).append(" - "); builder.append("Badge: ").append(badges.getBadge(dataObject.get("badgerank").getAsString())) .append(" - "); builder.append("Played: ").append(dataObject.get("played").getAsInt()).append(" - "); builder.append("Won: ").append(dataObject.get("won").getAsInt()); builder.append(" ("); builder.append( (int) ((dataObject.get("won").getAsDouble() / dataObject.get("played").getAsDouble()) * 100)); builder.append("%) - "); builder.append("Judgement wins: ").append(dataObject.get("limitedwon").getAsInt()).append(" - "); builder.append("Ranked wins: ").append(dataObject.get("rankedwon").getAsInt()).append(" - "); builder.append("Last game played: ").append(parseTime(dataObject.get("lastgame").getAsInt())); event.respond(builder.toString()); } catch (IOException | JsonSyntaxException ex) { extension.getLogger().log(Level.SEVERE, "Error on getting player stats for Scrolls for " + name, ex); event.respond("Error on getting player stats: " + ex.getLocalizedMessage()); } }
From source file:eu.artist.methodology.mpt.cheatsheet.actions.DownloadMATReportAction.java
@Override public void run(String[] params, ICheatSheetManager arg1) { //String url = "http://54.196.142.179:8080/ArtistEva/webresources/question/getmpt"; InputStream in = null;//w ww .jav a2 s . c o m try { URL url = new URL( "http://54.196.142.179:8080/ArtistEva/webresources/question/getmpt?login=yosu¶ms={%22ts%22:1412763746529}&hash=e4ecd6a297c01e9cca5a0da0e018a5de9f9ddfa6bd3e13b727df85ba542d11af74c32326320c65ca2de3441b488a09c9f6634ca1f83575be015504dd4168eac0"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); String output; String strXml; StringBuilder builder = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream()))); while ((output = br.readLine()) != null) { builder.append(output); } strXml = builder.toString(); System.out.println("MAT report:" + strXml); PrintWriter out = new PrintWriter("MAT_report.txt"); out.println(strXml); out.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:net.nikr.eve.jeveasset.io.online.CitadelGetter.java
private void updateCache(UpdateTask updateTask) { LOG.info("Citadels updating:"); if (citadelSettings.getNextUpdate().after(new Date()) && !Settings.get().isForceUpdate() && !Program.isForceUpdate()) { //Check if we can update now if (updateTask != null) { updateTask.addError(DialoguesUpdate.get().citadel(), "Not allowed yet.\r\n(Fix: Just wait a bit)"); }//from w w w. j av a 2 s . c o m LOG.info(" Citadels failed to update (NOT ALLOWED YET)"); return; } //Update citadel InputStream in = null; try { //Update from API ObjectMapper mapper = new ObjectMapper(); //create once, reuse URL url = new URL(URL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestProperty("Accept-Encoding", "gzip"); long contentLength = con.getContentLengthLong(); String contentEncoding = con.getContentEncoding(); InputStream inputStream = new UpdateTaskInputStream(con.getInputStream(), contentLength, updateTask); if ("gzip".equals(contentEncoding)) { in = new GZIPInputStream(inputStream); } else { in = inputStream; } Map<Long, Citadel> results = mapper.readValue(in, new TypeReference<Map<Long, Citadel>>() { }); if (results != null) { //Updated OK for (Map.Entry<Long, Citadel> entry : results.entrySet()) { citadelSettings.put(entry.getKey(), entry.getValue()); } } citadelSettings.setNextUpdate(); saveXml(); LOG.info(" Updated citadels for jEveAssets"); } catch (IOException ex) { if (updateTask != null) { updateTask.addError(DialoguesUpdate.get().citadel(), ex.getMessage()); } LOG.error(" Citadels failed to update", ex); } finally { if (in != null) { try { in.close(); } catch (IOException ex) { //No problem... } } } }