List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java
private static String sendGET(URL url, HttpURLConnection con, String userAgent, String tokenId) throws IOException { con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", userAgent); con.setRequestProperty("X-Auth-Token", tokenId); logger.log(Level.INFO, "Sending GET request to URL : {0}", url); int responseCode = con.getResponseCode(); logger.log(Level.INFO, "Response Code : {0}", responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine;/*from w w w.j a v a2 s . c om*/ StringBuilder responseStr = new StringBuilder(); while ((inputLine = in.readLine()) != null) { responseStr.append(inputLine); } in.close(); return responseStr.toString(); }
From source file:com.evrythng.java.wrapper.util.FileUtils.java
private static HttpURLConnection getConnectionForPrivateUpload(final URL url, final String contentType) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpPut.METHOD_NAME); connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, contentType); connection.setRequestProperty(X_AMZ_ACL_HEADER_NAME, X_AMZ_ACL_HEADER_VALUE_PRIVATE); connection.setDoOutput(true);/* ww w.j a v a2 s. c o m*/ connection.connect(); return connection; }
From source file:com.meetingninja.csse.database.MeetingDatabaseAdapter.java
public static Meeting getMeetingInfo(String meetingID) throws IOException { // Server URL setup String _url = getBaseUri().appendPath(meetingID).build().toString(); // Establish connection URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod("GET"); addRequestHeader(conn, false);//from ww w .j a v a 2s . c o m // Get server response int responseCode = conn.getResponseCode(); String response = getServerResponse(conn); JsonNode meetingNode = MAPPER.readTree(response); Meeting ret = parseMeeting(meetingNode); ret.setID(meetingID); return ret; }
From source file:com.vaguehope.onosendai.util.HttpHelper.java
private static <R> R fetchWithFollowRedirects(final Method method, final URL url, final HttpStreamHandler<R> streamHandler, final int redirectCount) throws IOException, URISyntaxException { final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try {/* w ww . ja v a2 s. c o m*/ connection.setRequestMethod(method.toString()); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_CONNECT_TIMEOUT_SECONDS)); connection.setReadTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_READ_TIMEOUT_SECONDS)); connection.setRequestProperty("User-Agent", "curl/1"); // Make it really clear this is not a browser. //connection.setRequestProperty("Accept-Encoding", "identity"); This fixes missing Content-Length headers but feels wrong. connection.connect(); InputStream is = null; try { final int responseCode = connection.getResponseCode(); // For some reason some devices do not follow redirects. :( if (responseCode == 301 || responseCode == 302 || responseCode == 303 || responseCode == 307) { // NOSONAR not magic numbers. Its HTTP spec. if (redirectCount >= MAX_REDIRECTS) throw new TooManyRedirectsException(responseCode, url, MAX_REDIRECTS); final String locationHeader = connection.getHeaderField("Location"); if (locationHeader == null) throw new HttpResponseException(responseCode, "Location header missing. Headers present: " + connection.getHeaderFields() + "."); connection.disconnect(); final URL locationUrl; if (locationHeader.toLowerCase(Locale.ENGLISH).startsWith("http")) { locationUrl = new URL(locationHeader); } else { locationUrl = url.toURI().resolve(locationHeader).toURL(); } return fetchWithFollowRedirects(method, locationUrl, streamHandler, redirectCount + 1); } if (responseCode < 200 || responseCode >= 300) { // NOSONAR not magic numbers. Its HTTP spec. throw new NotOkResponseException(responseCode, connection, url); } is = connection.getInputStream(); final int contentLength = connection.getContentLength(); if (contentLength < 1) LOG.w("Content-Length=%s for %s.", contentLength, url); return streamHandler.handleStream(connection, is, contentLength); } finally { IoHelper.closeQuietly(is); } } finally { connection.disconnect(); } }
From source file:com.mycompany.craftdemo.utility.java
public static JSONObject getAPIData(String apiURL) { try {//from w w w . j a va2 s.co m URL url = new URL(apiURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); StringBuilder sb = new StringBuilder(); String output; while ((output = br.readLine()) != null) sb.append(output); String res = sb.toString(); JSONParser parser = new JSONParser(); JSONObject json = null; try { json = (JSONObject) parser.parse(res); } catch (ParseException ex) { ex.printStackTrace(); } //resturn api data in json format return json; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:com.openforevent.main.UserPosition.java
public static Map<String, Object> userPositionByIP(DispatchContext ctx, Map<String, ? extends Object> context) throws IOException { URL url = new URL("http://api.ipinfodb.com/v3/ip-city/?" + "key=" + ipinfodb_key + "&" + "&ip=" + default_ip + "&format=xml"); //URL url = new URL("http://ipinfodb.com/ip_query.php"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // Set properties of the connection urlConnection.setRequestMethod("GET"); urlConnection.setDoInput(true);// w ww . j a v a 2 s. c om urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Retrieve the output int responseCode = urlConnection.getResponseCode(); InputStream inputStream; if (responseCode == HttpURLConnection.HTTP_OK) { inputStream = urlConnection.getInputStream(); } else { inputStream = urlConnection.getErrorStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, "UTF-8"); String theString = writer.toString(); Debug.logInfo("Get user position by IP stream is = ", theString); Map<String, Object> paramOut = FastMap.newInstance(); paramOut.put("stream", theString); return paramOut; }
From source file:Main.IrcBot.java
public static void postRequest(String pasteCode, PrintWriter out) { try {//from w w w .jav a 2s. c o m String url = "http://pastebin.com/raw.php?i=" + pasteCode; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = ""; // Send post request con.setDoOutput(true); 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())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine + "\n"); } in.close(); //print result System.out.println(response.toString()); if (response.length() > 0) { IrcBot.postGit(response.toString(), out); } else { out.println("PRIVMSG #learnprogramming :The PasteBin URL is not valid."); } } catch (Exception p) { } }
From source file:com.adanac.module.blog.api.HttpApiHelper.java
public static void baiduPush(int remain) { String pushUrl = DaoFactory.getDao(HtmlPageDao.class).findPushUrl(); if (pushUrl == null) { if (logger.isInfoEnabled()) { logger.info("all html page has been pushed!"); }/*from w ww.ja v a 2 s .c o m*/ return; } if (remain <= 0) { if (logger.isInfoEnabled()) { logger.info("there has no remain[" + remain + "]!"); } return; } if (logger.isInfoEnabled()) { logger.info("find push url : " + pushUrl); } String url = "http://data.zz.baidu.com/urls?site=" + site + "&token=" + token; try { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/plain"); OutputStream outputStream = connection.getOutputStream(); outputStream.write(pushUrl.getBytes("UTF-8")); outputStream.write("\r\n".getBytes("UTF-8")); outputStream.flush(); int status = connection.getResponseCode(); if (logger.isInfoEnabled()) { logger.info("baidu-push response code : " + status); } if (status == HttpServletResponse.SC_OK) { String response = IOUtil.read(connection.getInputStream()); if (logger.isInfoEnabled()) { logger.info("baidu-push response : " + response); } JSONObject result = JSONObject.fromObject(response); if (result.getInt("success") >= 1) { DaoFactory.getDao(HtmlPageDao.class).updateIsPush(pushUrl); } else { logger.warn("push url failed : " + pushUrl); } baiduPush(result.getInt("remain")); } else { logger.error("baidu-push error : " + IOUtil.read(connection.getErrorStream())); } } catch (Exception e) { logger.error("baidu push failed ...", e); } }
From source file:io.github.retz.web.JobRequestRouter.java
public static boolean statHTTPFile(String url, String name) { String addr = url.replace("files/browse", "files/download") + "%2F" + maybeURLEncode(name); HttpURLConnection conn = null; try {//from ww w . j ava2 s .c o m conn = (HttpURLConnection) new URL(addr).openConnection(); conn.setRequestMethod("HEAD"); conn.setDoOutput(false); LOG.debug(conn.getResponseMessage()); return conn.getResponseCode() == 200 || conn.getResponseCode() == 204; } catch (IOException e) { LOG.debug("Failed to fetch {}: {}", addr, e.toString()); return false; } finally { if (conn != null) { conn.disconnect(); } } }
From source file:com.zf.util.Post_NetNew.java
/** * ?//www.j a v a2 s .c o m * * @param pams * @param ip * @param port * @return * @throws Exception */ public static String pn(Map<String, String> pams, String ip, int port) throws Exception { if (null == pams) { return ""; } InetSocketAddress addr = new InetSocketAddress(ip, port); Proxy proxy = new Proxy(Type.HTTP, addr); String strtmp = "url"; URL url = new URL(pams.get(strtmp)); pams.remove(strtmp); strtmp = "body"; String body = pams.get(strtmp); pams.remove(strtmp); strtmp = "POST"; if (StringUtils.isEmpty(body)) strtmp = "GET"; HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(proxy); httpConn.setConnectTimeout(30000); httpConn.setReadTimeout(30000); httpConn.setUseCaches(false); httpConn.setRequestMethod(strtmp); for (String pam : pams.keySet()) { httpConn.setRequestProperty(pam, pams.get(pam)); } if ("POST".equals(strtmp)) { httpConn.setDoOutput(true); httpConn.setDoInput(true); DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream()); dos.writeBytes(body); dos.flush(); } int resultCode = httpConn.getResponseCode(); StringBuilder sb = new StringBuilder(); sb.append(resultCode).append("\n"); String readLine; InputStream stream; try { stream = httpConn.getInputStream(); } catch (Exception ignored) { stream = httpConn.getErrorStream(); } try { BufferedReader responseReader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); while ((readLine = responseReader.readLine()) != null) { sb.append(readLine).append("\n"); } } catch (Exception ignored) { } return sb.toString(); }