List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:com.arthurpitman.common.HttpUtils.java
/** * Connects to an HTTP resource using the get method. * @param url the URL to connect to.// w ww . ja v a 2 s .co m * @param requestProperties optional request properties, <code>null</code> if not required. * @return the resulting {@link HttpURLConnection}. * @throws IOException */ public static HttpURLConnection connectGet(final String url, final RequestProperty[] requestProperties) throws IOException { // setup connection HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setUseCaches(false); connection.setRequestMethod(GET_METHOD); addRequestProperties(connection, requestProperties); return connection; }
From source file:com.meetingninja.csse.database.NotesDatabaseAdapter.java
public static Note getNote(final String noteID) throws Exception { // Server URL setup String _url = getBaseUri().appendPath(noteID).build().toString(); // Establish connection URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.GET); addRequestHeader(conn, false);//from w ww . j a v a 2s. co m // Get server response int responseCode = conn.getResponseCode(); String response = getServerResponse(conn); JsonNode userNode = MAPPER.readTree(response); Note ret = parseNote(userNode); return ret; }
From source file:com.android.nunes.sophiamobile.gsm.GcmSender.java
public static void enviar(String msg, String token) { try {//from w w w. j a va 2 s .c om // Prepare JSON containing the GCM message content. What to send and where to send. JSONObject jGcmData = new JSONObject(); JSONObject jData = new JSONObject(); jData.put("message", msg.trim()); // Where to send GCM message. if (token != null) { jGcmData.put("to", token.trim()); } else { jGcmData.put("to", "/topics/global"); } // What to send in GCM message. jGcmData.put("data", jData); // Create connection to send GCM Message request. URL url = new URL("https://android.googleapis.com/gcm/send"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + API_KEY); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Send GCM message content. OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); String resp = IOUtils.toString(inputStream); System.out.println(resp); System.out.println("Check your device/emulator for notification or logcat for " + "confirmation of the receipt of the GCM message."); } catch (IOException e) { System.out.println("Unable to send GCM message."); System.out.println("Please ensure that API_KEY has been replaced by the server " + "API key, and that the device's registration token is correct (if specified)."); e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } }
From source file:com.meetingninja.csse.database.AgendaDatabaseAdapter.java
public static Agenda createAgenda(Agenda create) throws IOException { Agenda newAgenda = new Agenda(create); // Server URL setup String _url = getBaseUri().build().toString(); // Establish connection URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.POST); addRequestHeader(conn, true);/*from w w w. j a v a 2s . c o m*/ // prepare POST payload ByteArrayOutputStream json = new ByteArrayOutputStream(); // this type of print stream allows us to get a string easily PrintStream ps = new PrintStream(json); // Create a generator to build the JSON string JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8); // Build JSON Object jgen.writeStartObject(); // start agenda jgen.writeStringField(Keys.Agenda.TITLE, create.getTitle()); jgen.writeStringField(Keys.Agenda.MEETING, create.getAttachedMeetingID()); jgen.writeArrayFieldStart(Keys.Agenda.TOPIC); // start topics MAPPER.writeValue(jgen, create.getTopics()); // recursively does // subtopics jgen.writeEndArray(); // end topics jgen.writeEndObject(); // end agenda jgen.close(); // Get JSON Object payload from print stream String payload = json.toString("UTF8"); ps.close(); // Send payload int responseCode = sendPostPayload(conn, payload); String response = getServerResponse(conn); newAgenda = parseAgenda(MAPPER.readTree(response)); return newAgenda; }
From source file:eu.liveandgov.ar.utilities.OS_Utils.java
/** * Check if URL exists /* ww w . j a v a 2 s .c o m*/ * * @param urlSTR * @return */ public static boolean exists(String URLName) { try { HttpURLConnection.setFollowRedirects(false); // note : you may also need // HttpURLConnection.setInstanceFollowRedirects(false) HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection(); con.setRequestMethod("HEAD"); return (con.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { return false; } }
From source file:com.meetingninja.csse.database.NotesDatabaseAdapter.java
public static Boolean deleteNote(String noteID) throws IOException { String _url = getBaseUri().appendPath(noteID).build().toString(); URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.DELETE); addRequestHeader(conn, false);/*from www. j a v a 2s . co m*/ int responseCode = conn.getResponseCode(); String response = getServerResponse(conn); boolean result = false; JsonNode tree = MAPPER.readTree(response); if (!response.isEmpty()) { if (!tree.has(Keys.DELETED)) { result = true; } else { logError("note.del.err", tree); } } conn.disconnect(); return result; }
From source file:chen.android.toolkit.network.HttpConnection.java
/** * </br><b>title : </b> ????POST?? * </br><b>description :</b>????POST?? * </br><b>time :</b> 2012-7-8 ?4:34:08 * @param method ??/*from w w w . j a va 2 s.com*/ * @param url POSTURL * @param datas ???? * @return ??? * @throws IOException */ private static InputStream connect(String method, URL url, byte[]... datas) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod(method); conn.setUseCaches(false); conn.setInstanceFollowRedirects(true); conn.setConnectTimeout(6 * 1000); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); OutputStream outputStream = conn.getOutputStream(); for (byte[] data : datas) { outputStream.write(data); } outputStream.close(); return conn.getInputStream(); }
From source file:org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.ArduinoServiceUtils.java
public static String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext, boolean fireAndForgot) throws DeviceManagementException { String responseMsg = ""; String urlString = ArduinoConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext; if (log.isDebugEnabled()) { log.debug(urlString);/*from w ww . ja v a 2 s . co m*/ } if (!fireAndForgot) { HttpURLConnection httpConnection = getHttpConnection(urlString); try { httpConnection.setRequestMethod(HttpMethod.GET); } catch (ProtocolException e) { String errorMsg = "Protocol specific error occurred when trying to set method to GET" + " for:" + urlString; log.error(errorMsg); throw new DeviceManagementException(errorMsg, e); } responseMsg = readResponseFromGetRequest(httpConnection); } else { CloseableHttpAsyncClient httpclient = null; try { httpclient = HttpAsyncClients.createDefault(); httpclient.start(); HttpGet request = new HttpGet(urlString); final CountDownLatch latch = new CountDownLatch(1); Future<HttpResponse> future = httpclient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse httpResponse) { latch.countDown(); } @Override public void failed(Exception e) { latch.countDown(); } @Override public void cancelled() { latch.countDown(); } }); latch.await(); } catch (InterruptedException e) { if (log.isDebugEnabled()) { log.debug("Sync Interrupted"); } } finally { try { if (httpclient != null) { httpclient.close(); } } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed on close"); } } } } return responseMsg; }
From source file:Main.java
public static String stringFromHttpPost(String urlStr, String body) { HttpURLConnection conn; try {// ww w.j a va 2 s . c om URL e = new URL(urlStr); conn = (HttpURLConnection) e.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setInstanceFollowRedirects(true); conn.setRequestMethod("POST"); OutputStream os1 = conn.getOutputStream(); DataOutputStream out1 = new DataOutputStream(os1); out1.write(body.getBytes("UTF-8")); out1.flush(); conn.connect(); String line; BufferedReader reader; StringBuffer sb = new StringBuffer(); if ("gzip".equals(conn.getHeaderField("Content-Encoding"))) { reader = new BufferedReader( new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8")); } else { reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); } while ((line = reader.readLine()) != null) { sb.append(line); } return sb.toString(); } catch (Exception e) { e.printStackTrace(); logError(e.getMessage()); } return null; }
From source file:com.evrythng.java.wrapper.util.FileUtils.java
private static HttpURLConnection getConnectionForPublicUpload(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_PUBLIC_READ); connection.setDoOutput(true);/*from www . j ava 2 s . c o m*/ connection.connect(); return connection; }