List of usage examples for java.net HttpURLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:com.sun.socialsite.pojos.App.java
public static App readFromURL(URL url) throws Exception { HttpURLConnection con = (HttpURLConnection) (url.openConnection()); con.setDoOutput(false); // TODO: figure out why this is necessary for HTTPS URLs if (con instanceof HttpsURLConnection) { HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) { return true; } else { log.warn("URL Host: " + urlHostName + " vs. " + session.getPeerHost()); return false; }//from w ww . ja v a2s .co m } }; ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv); } con.connect(); if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new RuntimeException(con.getResponseMessage()); } InputStream in = con.getInputStream(); return readFromStream(in, url); }
From source file:com.codelanx.codelanxlib.util.auth.UUIDFetcher.java
/** * Creates a connection object for requesting a single profile name * /* w w w .j av a 2s .co m*/ * @since 0.1.0 * @version 0.1.0 * * @param name The name to request * @return The {@link HttpURLConnection} to Mojang's server * @throws IOException If there is a problem opening the stream, a malformed * URL, or if there is a ProtocolException */ private static HttpURLConnection createSingleProfileConnection(String name) throws IOException { URL url = new URL(String.format("https://api.mojang.com/users/profiles/minecraft/%s?at=0", name)); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setUseCaches(false); connection.setDoOutput(true); return connection; }
From source file:Main.java
/** * Connect to an HTTP URL and return the response as a string. * /*from ww w . j a va2 s . c o m*/ * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url - the resource to open: must be a welformed URL * @param method - the HTTP method to use ("GET", "POST", etc.) * @param params - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { // use method override params.putString("method", method); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8")); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }
From source file:controllers.base.Application.java
public static Result login(String redirectTo, boolean isGuest) { if (isGuest) { createWebSession();/* www. j av a 2 s . c o m*/ } 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.mingsoft.weixin.http.HttpClientConnectionManager.java
/** * ?/* w w w .jav a 2 s . c o m*/ * @param postUrl ? * @param param ? * @param method * @return null */ public static String request(String postUrl, String param, String method) { URL url; try { url = new URL(postUrl); HttpURLConnection conn; conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(30000); // ??) conn.setReadTimeout(30000); // ????) conn.setDoOutput(true); // post??http?truefalse conn.setDoInput(true); // ?httpUrlConnectiontrue conn.setUseCaches(false); // Post ? conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestMethod(method);// "POST"GET conn.setRequestProperty("Content-Length", param.length() + ""); String encode = "utf-8"; OutputStreamWriter out = null; out = new OutputStreamWriter(conn.getOutputStream(), encode); out.write(param); out.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { return null; } // ?? BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line = ""; StringBuffer strBuf = new StringBuffer(); while ((line = in.readLine()) != null) { strBuf.append(line).append("\n"); } in.close(); out.close(); return strBuf.toString(); } catch (MalformedURLException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
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 .ja va 2s. c o m 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:dlauncher.authorization.DefaultCredentialsManager.java
private static JSONObject makeRequest(URL url, JSONObject post, boolean ignoreErrors) throws ProtocolException, IOException, AuthorizationException { JSONObject obj = null;/*from w w w.j a v a 2s .c o m*/ try { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); con.setConnectTimeout(15 * 1000); con.setReadTimeout(15 * 1000); con.connect(); try (OutputStream out = con.getOutputStream()) { out.write(post.toString().getBytes(Charset.forName("UTF-8"))); } con.getResponseCode(); InputStream instr; instr = con.getErrorStream(); if (instr == null) { instr = con.getInputStream(); } byte[] data = new byte[1024]; int length; try (SizeLimitedByteArrayOutputStream bytes = new SizeLimitedByteArrayOutputStream(1024 * 4)) { try (InputStream in = new BufferedInputStream(instr)) { while ((length = in.read(data)) >= 0) { bytes.write(data, 0, length); } } byte[] rawBytes = bytes.toByteArray(); if (rawBytes.length != 0) { obj = new JSONObject(new String(rawBytes, Charset.forName("UTF-8"))); } else { obj = new JSONObject(); } if (!ignoreErrors && obj.has("error")) { String error = obj.getString("error"); String errorMessage = obj.getString("errorMessage"); String cause = obj.optString("cause", null); if ("ForbiddenOperationException".equals(error)) { if ("UserMigratedException".equals(cause)) { throw new UserMigratedException(errorMessage); } throw new ForbiddenOperationException(errorMessage); } throw new AuthorizationException( error + (cause != null ? "." + cause : "") + ": " + errorMessage); } return obj; } } catch (JSONException ex) { throw new InvalidResponseException(ex, obj); } }
From source file:com.example.cmput301.model.WebService.java
/** * Sets up http connection to the web server and returns the connection. * @return HttpURLConnection//www.j a va 2s. c om * @throws IOException */ private static HttpURLConnection setupConnections() throws IOException { // Send data URL url = new URL(uri); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoOutput(true); return conn; }
From source file:com.amazon.pay.impl.Util.java
/** * This method uses HttpURLConnection instance to make requests. * * @param method The HTTP method (GET,POST,PUT,etc.). * @param url The URL/*from w ww . j a v a 2s . com*/ * @param urlParameters URL Parameters * @param headers Header key-value pairs * @return ResponseData * @throws IOException */ public static ResponseData httpSendRequest(String method, String url, String urlParameters, Map<String, String> headers) throws IOException { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); if (headers != null && !headers.isEmpty()) { for (String key : headers.keySet()) { con.setRequestProperty(key, headers.get(key)); } } con.setDoOutput(true); con.setRequestMethod(method); if (urlParameters != null) { DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); } int responseCode = con.getResponseCode(); BufferedReader in; if (responseCode != 200) { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); } else { in = new BufferedReader(new InputStreamReader(con.getInputStream())); } String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine).append(LINE_SEPARATOR); } in.close(); return new ResponseData(responseCode, response.toString()); }
From source file:Main.java
public static void downloadImage(String imageUrl) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Log.d("TAG", "monted sdcard"); } else {//from w w w. ja va 2 s .c o m Log.d("TAG", "has no sdcard"); } HttpURLConnection con = null; FileOutputStream fos = null; BufferedOutputStream bos = null; BufferedInputStream bis = null; File imageFile = null; try { URL url = new URL(imageUrl); con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(5 * 1000); con.setReadTimeout(15 * 1000); con.setDoInput(true); con.setDoOutput(true); bis = new BufferedInputStream(con.getInputStream()); imageFile = new File(getImagePath(imageUrl)); fos = new FileOutputStream(imageFile); bos = new BufferedOutputStream(fos); byte[] b = new byte[1024]; int length; while ((length = bis.read(b)) != -1) { bos.write(b, 0, length); bos.flush(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (bis != null) { bis.close(); } if (bos != null) { bos.close(); } if (con != null) { con.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } if (imageFile != null) { } }