List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:com.meetingninja.csse.database.ProjectDatabaseAdapter.java
public static Project createProject(Project p) throws IOException, MalformedURLException { // Server URL setup String _url = getBaseUri().build().toString(); // establish connection URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); addRequestHeader(conn, true);/*ww w . j a v a2 s . c om*/ // 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(); jgen.writeStringField(Keys.Project.TITLE, p.getProjectTitle()); jgen.writeArrayFieldStart(Keys.Project.MEETINGS); for (Meeting meeting : p.getMeetings()) { jgen.writeStartObject(); jgen.writeStringField(Keys.Meeting.ID, meeting.getID()); jgen.writeEndObject(); } jgen.writeEndArray(); jgen.writeArrayFieldStart(Keys.Project.NOTES); for (Note note : p.getNotes()) { jgen.writeStartObject(); jgen.writeStringField(Keys.Note.ID, note.getID()); jgen.writeEndObject(); } jgen.writeEndArray(); jgen.writeArrayFieldStart(Keys.Project.MEMBERS); for (User member : p.getMembers()) { jgen.writeStartObject(); jgen.writeStringField(Keys.User.ID, member.getID()); jgen.writeEndObject(); } jgen.writeEndArray(); jgen.writeEndObject(); jgen.close(); // Get JSON Object payload from print stream String payload = json.toString("UTF8"); ps.close(); // send payload sendPostPayload(conn, payload); String response = getServerResponse(conn); // prepare to get the id of the created Meeting // Map<String, String> responseMap = new HashMap<String, String>(); /* * result should get valid={"meetingID":"##"} */ String result = new String(); if (!response.isEmpty()) { // responseMap = MAPPER.readValue(response, // new TypeReference<HashMap<String, String>>() { // }); JsonNode projectNode = MAPPER.readTree(response); if (!projectNode.has(Keys.Project.ID)) { result = "invalid"; } else result = projectNode.get(Keys.Project.ID).asText(); } if (!result.equalsIgnoreCase("invalid")) p.setProjectID(result); conn.disconnect(); return p; }
From source file:com.samsung.msf.youtubeplayer.client.util.FeedParser.java
/** * Given a string representation of a URL, sets up a connection and gets an input stream. */// w w w . j a v a2s .c o m public static InputStream downloadUrl(final URL url) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(NET_READ_TIMEOUT_MILLIS /* milliseconds */); conn.setConnectTimeout(NET_CONNECT_TIMEOUT_MILLIS /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); return conn.getInputStream(); }
From source file:controllers.base.Application.java
public static Result login(String redirectTo, boolean isGuest) { if (isGuest) { createWebSession();//from w w w .j a v a2 s . c om } else { String token = request().body().asFormUrlEncoded().get("token")[0]; String apiKey = Play.application().configuration().getString("rpx.apiKey"); String data; String response = null; try { data = String.format("token=%s&apiKey=%s&format=json", URLEncoder.encode(token, "UTF-8"), URLEncoder.encode(apiKey, "UTF-8")); URL url = new URL("https://rpxnow.com/api/v2/auth_info"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.connect(); OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); osw.write(data); osw.close(); response = IOUtils.toString(conn.getInputStream()); } catch (IOException e) { throw new IllegalArgumentException(e); } JsonNode profile = Json.parse(response).path("profile"); String identifier = profile.path("identifier").asText(); WebUser user = WebUser.find.where().like("providerId", identifier).findUnique(); if (user == null) { user = new WebUser().setProviderId(identifier).setProfile(Json.stringify(profile)); user.save(); } createWebSession(user); } return postLoginRedirect(redirectTo); }
From source file:com.gallatinsystems.common.util.S3Util.java
public static boolean put(String bucketName, String objectKey, byte[] data, String contentType, boolean isPublic, String awsAccessId, String awsSecretKey) throws IOException { final byte[] md5Raw = MD5Util.md5(data); final String md5Base64 = Base64.encodeBase64String(md5Raw).trim(); final String md5Hex = MD5Util.toHex(md5Raw); final String date = getDate(); final String payloadStr = isPublic ? PUT_PAYLOAD_PUBLIC : PUT_PAYLOAD_PRIVATE; final String payload = String.format(payloadStr, md5Base64, contentType, date, bucketName, objectKey); final String signature = MD5Util.generateHMAC(payload, awsSecretKey); final URL url = new URL(String.format(S3_URL, bucketName, objectKey)); OutputStream out = null;/*from w w w . j ava 2s . c o m*/ HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("PUT"); conn.setRequestProperty("Content-MD5", md5Base64); conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Date", date); if (isPublic) { // If we don't send this header, the object will be private by default conn.setRequestProperty("x-amz-acl", "public-read"); } conn.setRequestProperty("Authorization", "AWS " + awsAccessId + ":" + signature); out = new BufferedOutputStream(conn.getOutputStream()); IOUtils.copy(new ByteArrayInputStream(data), out); out.flush(); int status = conn.getResponseCode(); if (status != 200 && status != 201) { log.severe("Error uploading file: " + url.toString()); log.severe(IOUtils.toString(conn.getInputStream())); return false; } String etag = conn.getHeaderField("ETag"); etag = etag != null ? etag.replaceAll("\"", "") : null;// Remove quotes if (!md5Hex.equals(etag)) { log.severe("ETag comparison failed. Response ETag: " + etag + "Locally computed MD5: " + md5Hex); return false; } return true; } finally { if (conn != null) { conn.disconnect(); } IOUtils.closeQuietly(out); } }
From source file:com.qsoft.components.gallery.utils.GalleryUtils.java
private static InputStream OpenHttpConnection(String strURL) throws IOException { InputStream inputStream = null; URL url = new URL(strURL); URLConnection conn = url.openConnection(); try {//from w ww . j av a 2 s. c om HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setRequestMethod("GET"); httpConn.connect(); if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) { inputStream = httpConn.getInputStream(); } } catch (Exception ex) { Log.e("error", ex.toString()); } return inputStream; }
From source file:com.example.makerecg.NetworkUtilities.java
/** * Connects to the SampleSync test server, authenticates the provided * username and password.// ww w. j a v a 2s. co m * This is basically a standard OAuth2 password grant interaction. * * @param username The server account username * @param password The server account password * @return String The authentication token returned by the server (or null) */ public static String authenticate(String username, String password) { String token = null; try { Log.i(TAG, "Authenticating to: " + AUTH_URI); URL urlToRequest = new URL(AUTH_URI); HttpURLConnection conn = (HttpURLConnection) urlToRequest.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("grant_type", "password")); params.add(new BasicNameValuePair("client_id", "CLIENT_ID")); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getQuery(params)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { String response = ""; String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } br.close(); // Response body will look something like this: // { // "token_type": "bearer", // "access_token": "0dd18fd38e84fb40e9e34b1f82f65f333225160a", // "expires_in": 3600 // } JSONObject jresp = new JSONObject(new JSONTokener(response)); token = jresp.getString("access_token"); } else { Log.e(TAG, "Error authenticating"); token = null; } } catch (Exception e) { e.printStackTrace(); } finally { Log.v(TAG, "getAuthtoken completing"); } return token; }
From source file:com.google.api.ads.adwords.awreporting.server.appengine.exporter.ReportExporterAppEngine.java
public static void html2PdfOverNet(InputStream htmlSource, ReportWriter reportWriter) { try {/*from w ww. j a v a 2 s .co m*/ URL url = new URL(HTML_2_PDF_SERVER_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/html"); connection.setRequestProperty("charset", "utf-8"); connection.setUseCaches(false); DataOutputStream send = new DataOutputStream(connection.getOutputStream()); send.write(IOUtils.toByteArray(htmlSource)); send.flush(); // Read from connection reportWriter.write(connection.getInputStream()); send.close(); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
From source file:bluevia.SendSMS.java
public static void setFacebookWallPost(String userEmail, String post) { try {/*w w w . ja va 2 s . com*/ Properties facebookAccount = Util.getNetworkAccount(userEmail, Util.FaceBookOAuth.networkID); if (facebookAccount != null) { String access_key = facebookAccount.getProperty(Util.FaceBookOAuth.networkID + ".access_key"); com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate(); Entity blueviaUser = Util.getUser(userEmail); //FIXME URL fbAPI = new URL( "https://graph.facebook.com/" + (String) blueviaUser.getProperty("alias") + "/feed"); HttpURLConnection request = (HttpURLConnection) fbAPI.openConnection(); String content = String.format("access_token=%s&message=%s", access_key, URLEncoder.encode(post, "UTF-8")); request.setRequestMethod("POST"); request.setRequestProperty("Content-Type", "javascript/text"); request.setRequestProperty("Content-Length", "" + Integer.toString(content.getBytes().length)); request.setDoOutput(true); request.setDoInput(true); OutputStream os = request.getOutputStream(); os.write(content.getBytes()); os.flush(); os.close(); BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); int rc = request.getResponseCode(); if (rc == HttpURLConnection.HTTP_OK) { StringBuffer body = new StringBuffer(); String line; do { line = br.readLine(); if (line != null) body.append(line); } while (line != null); JSONObject id = new JSONObject(body.toString()); } else log.severe( String.format("Error %d posting FaceBook wall:%s\n", rc, request.getResponseMessage())); } } catch (Exception e) { log.severe(String.format("Exception posting FaceBook wall: %s", e.getMessage())); } }
From source file:jfutbol.com.jfutbol.GcmSender.java
public static void SendNotification(int userId, int notificationCounter) { String msg[] = new String[2]; if (notificationCounter > 1) msg = new String[] { "Tienes " + notificationCounter + " nuevas notificaciones.", "/topics/" + userId }; else// w w w. jav a 2 s. c om msg = new String[] { "Tienes " + notificationCounter + " nueva notificacion.", "/topics/" + userId }; if (msg.length < 1 || msg.length > 2 || msg[0] == null) { System.err.println("usage: ./gradlew run -Pmsg=\"MESSAGE\" [-Pto=\"DEVICE_TOKEN\"]"); System.err.println(""); System.err.println( "Specify a test message to broadcast via GCM. If a device's GCM registration token is\n" + "specified, the message will only be sent to that device. Otherwise, the message \n" + "will be sent to all devices subscribed to the \"global\" topic."); System.err.println(""); System.err.println( "Example (Broadcast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\""); System.err.println(""); System.err.println("Example (Unicast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\""); System.exit(1); } try { // 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[0].trim()); // Where to send GCM message. if (msg.length > 1 && msg[1] != null) { jGcmData.put("to", msg[1].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); updateNotificationAsSent(userId); 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)."); log.error(e.getMessage()); e.printStackTrace(); } }
From source file:com.example.makerecg.NetworkUtilities.java
/** * Perform 2-way sync with the server-side ADSampleFrames. We send a request that * includes all the locally-dirty contacts so that the server can process * those changes, and we receive (and return) a list of contacts that were * updated on the server-side that need to be updated locally. * * @param account The account being synced * @param authtoken The authtoken stored in the AccountManager for this * account//from w w w. j a va 2 s . c o m * @param serverSyncState A token returned from the server on the last sync * @param dirtyFrames A list of the frames to send to the server * @return A list of frames that we need to update locally */ public static List<ADSampleFrame> syncSampleFrames(Account account, String authtoken, long serverSyncState, List<ADSampleFrame> dirtyFrames) throws JSONException, ParseException, IOException, AuthenticationException { List<JSONObject> jsonFrames = new ArrayList<JSONObject>(); for (ADSampleFrame frame : dirtyFrames) { jsonFrames.add(frame.toJSONObject()); } JSONArray buffer = new JSONArray(jsonFrames); JSONObject top = new JSONObject(); top.put("data", buffer); // Create an array that will hold the server-side ADSampleFrame // that have been changed (returned by the server). final ArrayList<ADSampleFrame> serverDirtyList = new ArrayList<ADSampleFrame>(); // Send the updated frames data to the server //Log.i(TAG, "Syncing to: " + SYNC_URI); URL urlToRequest = new URL(SYNC_URI); HttpURLConnection conn = (HttpURLConnection) urlToRequest.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", "Bearer " + authtoken); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(top.toString(1)); writer.flush(); writer.close(); os.close(); //Log.i(TAG, "body="+top.toString(1)); int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { // Our request to the server was successful - so we assume // that they accepted all the changes we sent up, and // that the response includes the contacts that we need // to update on our side... // TODO: Only uploading data for now ... String response = ""; String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } br.close(); //Log.i(TAG, "response="+response); /* final JSONArray serverContacts = new JSONArray(response); Log.d(TAG, response); for (int i = 0; i < serverContacts.length(); i++) { ADSampleFrame rawContact = ADSampleFrame.valueOf(serverContacts.getJSONObject(i)); if (rawContact != null) { serverDirtyList.add(rawContact); } } */ } else { if (responseCode == HttpsURLConnection.HTTP_UNAUTHORIZED) { Log.e(TAG, "Authentication exception in while uploading data"); throw new AuthenticationException(); } else { Log.e(TAG, "Server error in sending sample frames: " + responseCode); throw new IOException(); } } return null; }