List of usage examples for java.net URLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:game.Clue.JerseyClient.java
public JSONObject getGameState() { JSONObject Object = null;/*from w w w. j av a 2 s. c om*/ try { URL url = new URL( "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/player1"); URLConnection connection = url.openConnection(); connection.setDoInput(true); //setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); Object = new JSONObject(in.readLine()); //; // JsonParser parser=new JsonParser(in.readLine()); // while (in.readLine() != null) { //} // System.out.print(in.readLine()); System.out.println(Object.getJSONArray("players").getJSONObject(0).getString("character")); System.out.println("\nREST Service Invoked Successfully..GET Request Sent"); //sendPUT(); //send JSON to Parser //Parser=new JsonParser(in.readLine()); //System.out.println("Parser called"); // sendPUT(); //close connection // in.close(); } catch (Exception e) { System.out.println("\nError while calling REST Service"); System.out.println(e); } return Object; }
From source file:org.omegat.languagetools.LanguageToolNetworkBridge.java
@SuppressWarnings("unchecked") protected List<Object> getSupportedLanguages() throws Exception { // This is a really stupid way to get the /languages endpoint URL, but it'll do for now. String langsUrl = serverUrl.replace(CHECK_PATH, LANGS_PATH); URL url = new URL(langsUrl); URLConnection conn = url.openConnection(); conn.setRequestProperty("User-Agent", OStrings.getNameAndVersion()); conn.setDoOutput(true);/*from w w w .j a v a 2 s .c o m*/ checkHttpError(conn); String json = ""; try (InputStream in = conn.getInputStream()) { json = IOUtils.toString(in, StandardCharsets.UTF_8); } return (List<Object>) JsonParser.parse(json); }
From source file:game.Clue.JerseyClient.java
public void requestLogintoServer(String name) { try {//ww w . j a va2 s . com for (int i = 0; i < 6; i++) { JSONObject jsonObject = new JSONObject(name); URL url = new URL( "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/player" + i); URLConnection connection = url.openConnection(); connection.setDoOutput(true); //setDoOutput(true); connection.setRequestProperty("PUT", "application/json"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(jsonObject.toString()); System.out.println("Sent PUT message for logging into server"); out.close(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.messic.server.api.tagwizard.discogs.DiscogsTAGWizardPlugin.java
private Album getAlbum(String id) { String baseURL = "http://api.discogs.com/releases/" + id; try {/*from w w w.j a v a 2 s . c o m*/ URL url = new URL(baseURL); Proxy proxy = getProxy(); URLConnection uc = (proxy != null ? url.openConnection(proxy) : url.openConnection()); uc.setRequestProperty("User-Agent", "Messic/1.0 +http://spheras.github.io/messic/"); Album album = new Album(); album.name = ""; album.author = ""; album.comments = "Info obtained by Discogs provider (http://www.discogs.com/)"; album.year = 1900; album.genre = ""; JsonFactory jsonFactory = new JsonFactory(); // or, for data binding, JsonParser jParser = jsonFactory.createParser(uc.getInputStream()); while (jParser.nextToken() != null) { String fieldname = jParser.getCurrentName(); if ("title".equals(fieldname)) { jParser.nextToken(); album.name = jParser.getText(); } if ("year".equals(fieldname)) { jParser.nextToken(); try { album.year = Integer.valueOf(jParser.getText()); } catch (Exception e) { album.year = 0; } } if ("notes".equals(fieldname)) { jParser.nextToken(); album.comments = jParser.getText(); } if ("genres".equals(fieldname)) { jParser.nextToken(); jParser.nextToken(); album.genre = jParser.getText(); do { jParser.nextToken(); } while (!"genres".equals(jParser.getCurrentName())); } if ("artists".equals(fieldname)) { jParser.nextToken(); while (!"name".equals(jParser.getCurrentName())) { jParser.nextToken(); } jParser.nextToken(); album.author = jParser.getText(); do { jParser.nextToken(); } while (!"artists".equals(jParser.getCurrentName())); } if ("tracklist".equals(fieldname)) { album.songs = new ArrayList<Song>(); do { Song newsong = new Song(); int tracknumber = 1; while (jParser.nextToken() != JsonToken.END_OBJECT) { String trackfieldname = jParser.getCurrentName(); if ("extraartists".equals(trackfieldname)) { do { while (jParser.nextToken() != JsonToken.END_OBJECT) { } jParser.nextToken(); } while (!"extraartists".equals(jParser.getCurrentName())); } if ("position".equals(trackfieldname)) { jParser.nextToken(); try { newsong.track = Integer.valueOf(jParser.getText()); } catch (Exception e) { newsong.track = tracknumber; } tracknumber++; } if ("title".equals(trackfieldname)) { jParser.nextToken(); newsong.name = jParser.getText(); } } album.songs.add(newsong); jParser.nextToken(); } while (!"tracklist".equals(jParser.getCurrentName())); jParser.nextToken(); } } return album; } catch (Exception e) { log.error("failed!", e); } return null; }
From source file:net.solarnetwork.node.support.HttpClientSupport.java
/** * HTTP POST data as {@code application/x-www-form-urlencoded} (e.g. a web * form) to a URL./*from ww w .ja v a 2s .c o m*/ * * @param url * the URL to post to * @param accept * the value to use for the Accept HTTP header * @param data * the data to encode and send as the body of the HTTP POST * @return the URLConnection after the post data has been sent * @throws IOException * if any IO error occurs * @throws RuntimeException * if the HTTP response code is not within the 200 - 299 range */ protected URLConnection postXWWWFormURLEncodedData(String url, String accept, Map<String, ?> data) throws IOException { URLConnection conn = getURLConnection(url, HTTP_METHOD_POST, accept); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String body = xWWWFormURLEncoded(data); log.trace("Encoded HTTP POST data {} as {}", data, body); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); FileCopyUtils.copy(new StringReader(body), out); if (conn instanceof HttpURLConnection) { HttpURLConnection http = (HttpURLConnection) conn; int status = http.getResponseCode(); if (status < 200 || status > 299) { throw new RuntimeException("HTTP result status not in the 200-299 range: " + http.getResponseCode() + " " + http.getResponseMessage()); } } return conn; }
From source file:org.jvnet.hudson.update_center.MavenRepositoryImpl.java
/** * Loads a remote repository index (.zip or .gz), convert it to Lucene index and return it. *//*from w w w . j a va 2 s . c om*/ private File loadIndex(String id, URL url) throws IOException, UnsupportedExistingLuceneIndexException { File dir = new File(new File(System.getProperty("java.io.tmpdir")), "maven-index/" + id); File local = new File(dir, "index" + getExtension(url)); File expanded = new File(dir, "expanded"); URLConnection con = url.openConnection(); if (url.getUserInfo() != null) { con.setRequestProperty("Authorization", "Basic " + new sun.misc.BASE64Encoder().encode(url.getUserInfo().getBytes())); } if (!expanded.exists() || !local.exists() || (local.lastModified() != con.getLastModified() && !offlineIndex)) { System.out.println("Downloading " + url); // if the download fail in the middle, only leave a broken tmp file dir.mkdirs(); File tmp = new File(dir, "index_" + getExtension(url)); FileOutputStream o = new FileOutputStream(tmp); IOUtils.copy(con.getInputStream(), o); o.close(); if (expanded.exists()) FileUtils.deleteDirectory(expanded); expanded.mkdirs(); if (url.toExternalForm().endsWith(".gz")) { System.out.println("Reconstructing index from " + url); FSDirectory directory = FSDirectory.getDirectory(expanded); NexusIndexWriter w = new NexusIndexWriter(directory, new NexusAnalyzer(), true); FileInputStream in = new FileInputStream(tmp); try { IndexDataReader dr = new IndexDataReader(in); IndexDataReadResult result = dr.readIndex(w, new DefaultIndexingContext(id, id, null, expanded, null, null, NexusIndexer.DEFAULT_INDEX, true)); } finally { IndexUtils.close(w); IOUtils.closeQuietly(in); directory.close(); } } else if (url.toExternalForm().endsWith(".zip")) { Expand e = new Expand(); e.setSrc(tmp); e.setDest(expanded); e.execute(); } else { throw new UnsupportedOperationException("Unsupported index format: " + url); } // as a proof that the expansion was properly completed tmp.renameTo(local); local.setLastModified(con.getLastModified()); } else { System.out.println("Reusing the locally cached " + url + " at " + local); } return expanded; }
From source file:org.botlibre.util.Utils.java
public static InputStream openStream(URL url, int timeout) throws IOException { URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout);//w w w . j a va 2 s . c o m return connection.getInputStream(); }
From source file:com.moviejukebox.tools.WebBrowser.java
public URLConnection openProxiedConnection(URL url) throws IOException { URLConnection cnx = url.openConnection(YamjHttpClientBuilder.getProxy()); if (PROXY_USERNAME != null) { cnx.setRequestProperty("Proxy-Authorization", ENCODED_PASSWORD); }/*from ww w . j a va 2s . c o m*/ cnx.setConnectTimeout(TIMEOUT_CONNECT); cnx.setReadTimeout(TIMEOUT_READ); return cnx; }
From source file:com.typhoon.newsreader.engine.ChannelRefresh.java
public long syncDB(Handler h, long id, String rssurl) throws Exception { mHandler = h;//from w ww. j a v a2 s . co m mID = id; mRSSURL = rssurl; SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(this); xr.setErrorHandler(this); URL url = new URL(mRSSURL); URLConnection c = url.openConnection(); c.setRequestProperty("User-Agent", "Android/m3-rc37a"); xr.parse(new InputSource(c.getInputStream())); return mID; }
From source file:com.sabre.hack.travelachievementgame.DSCommHandler.java
@SuppressWarnings("deprecation") public String sendRequest(String payLoad, String authToken) { URLConnection conn = null; String strRet = null;/* ww w .j ava2 s . c o m*/ try { URL urlConn = new URL(payLoad); conn = null; conn = urlConn.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Authorization", "Bearer " + authToken); conn.setRequestProperty("Accept", "application/json"); DataInputStream dataIn = new DataInputStream(conn.getInputStream()); String strChunk = ""; StringBuilder sb = new StringBuilder(""); while (null != ((strChunk = dataIn.readLine()))) sb.append(strChunk); strRet = sb.toString(); } catch (MalformedURLException e) { // TODO Auto-generated catch block System.out.println("MalformedURLException in DSCommHandler"); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("IOException in DSCommHandler: " + conn.getHeaderField(0)); // e.printStackTrace(); } return strRet; }