List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:com.magnet.plugin.common.helpers.URLHelper.java
public static String checkURLConnection(String urlS, String username, String password) { String status = "Error connection to server!"; FormattedLogger logger = new FormattedLogger(URLHelper.class); logger.append("checkURLConnection:" + urlS); try {/*from w ww.ja v a2 s . c o m*/ URL url = new URL(urlS); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (username != null && username.trim().length() > 0 && password != null && password.trim().length() > 0) { final String authString = username + ":" + password; conn.setRequestProperty("Authorization", "Basic " + Base64.encode(authString.getBytes())); } conn.setRequestMethod("GET"); conn.setDoInput(true); status = "" + conn.getResponseCode(); logger.append("Response code:" + status); logger.showInfoLog(); } catch (Exception e) { logger.append(">>>" + e.getClass().getName() + " message: " + e.getMessage()); logger.showErrorLog(); } return status; }
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 ww w .j av a 2s. co 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.thyn.backend.gcm.GcmSender.java
public static String sendMessageToDeviceGroup(String to, String message, String sender, Long profileID, Long taskID) {/*from w w w. j a va 2s . c o m*/ String resp = null; 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", message); jData.put("sender", sender); jData.put("profileID", profileID); jData.put("taskID", taskID); // Where to send GCM message. if (to != null && message != null) { jGcmData.put("to", to.trim()); } else { Logger.logError("Error", new NullPointerException()); return null; } // What to send in GCM message. jGcmData.put("data", jData); // Create connection to send GCM Message request. URL url = new URL("https://gcm-http.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); System.out.println("The payload is: " + jGcmData.toString()); // Send GCM message content. OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); resp = IOUtils.toString(inputStream); if (resp == null || resp.trim().equals("")) { System.out.println("Got a Null Response from the server. Unable to send GCM message."); return null; } else { System.out.println("the response from GCM server is: " + resp); System.out.println("Check your device/emulator for notification or logcat for " + "confirmation of the receipt of the GCM message."); } JSONObject jResp = null; try { jResp = new JSONObject(resp); } catch (JSONException jsone) { jsone.printStackTrace(); } int rSuccess = jResp.getInt("success"); int rFailure = jResp.getInt("failure"); if (rSuccess == 0 && rFailure > 0) System.out.println( "Failed sending message to the recipient. Total no. of devices for the user. " + rFailure); else if (rSuccess > 0 && rFailure == 0) System.out.println("Success sending message to all receipients. Total no. of devices for the user " + rSuccess); else System.out.println("Partial success. Success sending to " + rSuccess + " devices. And failed sending to " + rFailure + " devices"); } catch (IOException e) { Logger.logError("Unable to send GCM message.", e); } return resp; }
From source file:eu.geopaparazzi.library.network.NetworkUtilities.java
/** * Sends a string via POST to a given url. * /* ww w. j a v a 2s .c o m*/ * @param urlStr the url to which to send to. * @param string the string to send as post body. * @param user the user or <code>null</code>. * @param password the password or <code>null</code>. * @return the response. * @throws Exception */ public static String sendPost(String urlStr, String string, String user, String password) throws Exception { BufferedOutputStream wr = null; HttpURLConnection conn = null; try { conn = makeNewConnection(urlStr); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); // conn.setChunkedStreamingMode(0); conn.setUseCaches(false); if (user != null && password != null) { conn.setRequestProperty("Authorization", getB64Auth(user, password)); } conn.connect(); // Make server believe we are form data... wr = new BufferedOutputStream(conn.getOutputStream()); byte[] bytes = string.getBytes(); wr.write(bytes); wr.flush(); int responseCode = conn.getResponseCode(); StringBuilder returnMessageBuilder = new StringBuilder(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); while (true) { String line = br.readLine(); if (line == null) break; returnMessageBuilder.append(line + "\n"); } br.close(); } return returnMessageBuilder.toString(); } catch (Exception e) { e.printStackTrace(); throw e; } finally { if (conn != null) conn.disconnect(); } }
From source file:com.mnt.base.util.HttpUtil.java
public static String processPostRequest2Text(String url, Map<String, Object> parameters, Map<String, String> headerValue) { HttpURLConnection connection = null; try {//www .j ava2 s. co m connection = (HttpURLConnection) new URL(url).openConnection(); } catch (IOException e) { log.error("Error while process http get request.", e); } if (connection != null) { try { connection.setRequestMethod("POST"); connection.setDoOutput(true); } catch (ProtocolException e) { log.error("should not happen to get error while set the request method as GET.", e); } if (!CommonUtil.isEmpty(headerValue)) { for (String key : headerValue.keySet()) { connection.setRequestProperty(key, headerValue.get(key)); } } // need to specify the content type for post request connection.setRequestProperty("Content-Type", "application/json"); setTimeout(connection); String resultStr = null; try { connection.connect(); if (parameters != null) { String jsonParams = null; try { jsonParams = JSONTool.convertObjectToJson(parameters); } catch (Exception e) { log.error("error while process parameters to json string.", e); } if (jsonParams != null) { connection.getOutputStream().write(jsonParams.getBytes()); connection.getOutputStream().flush(); } } resultStr = readData(connection.getInputStream()); } catch (IOException e) { log.error("fail to connect to url: " + url, e); } finally { connection.disconnect(); } return resultStr; } return null; }
From source file:vocab.VocabUtils.java
/** * Jena fails to load models in https with content negotiation. Therefore I do * the negotiation here directly/* w ww . j a v a 2s. c o m*/ */ private static void doContentNegotiation(OntModel model, Vocabulary v, String accept, String serialization) { try { model.read(v.getUri(), null, serialization); } catch (Exception e) { try { System.out.println("Failed to read the ontology. Doing content negotiation"); URL url = new URL(v.getUri()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Accept", accept); int status = connection.getResponseCode(); if (status == HttpURLConnection.HTTP_SEE_OTHER || status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM) { String newUrl = connection.getHeaderField("Location"); //v.setUri(newUrl); connection = (HttpURLConnection) new URL(newUrl).openConnection(); connection.setRequestProperty("Accept", accept); InputStream in = (InputStream) connection.getInputStream(); model.read(in, null, serialization); } } catch (Exception e2) { System.out.println("Failed to read the ontology"); } } }
From source file:com.mingsoft.weixin.util.UploadDownUtils.java
/** * ? /* ww w . j av a 2s . c o m*/ * * @return */ @Deprecated public static String downMedia(String access_token, String msgType, String media_id, String path) { String localFile = null; // SimpleDateFormat df = new SimpleDateFormat("/yyyyMM/"); try { String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + access_token + "&media_id=" + media_id; // log.error(path); // ? ? URL urlObj = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); String xx = conn.getHeaderField("Content-disposition"); try { log.debug("===? +==?==" + xx); if (xx == null) { InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8")); String line = null; String result = null; while ((line = reader.readLine()) != null) { if (result == null) { result = line; } else { result += line; } } System.out.println(result); JSONObject dataJson = JSONObject.parseObject(result); return dataJson.getString("errcode"); } } catch (Exception e) { } if (conn.getResponseCode() == 200) { String Content_disposition = conn.getHeaderField("Content-disposition"); InputStream inputStream = conn.getInputStream(); // // ? // Long fileSize = conn.getContentLengthLong(); // + String savePath = path + "/" + msgType; // ?? String fileName = StringUtil.getDateSimpleStr() + Content_disposition.substring(Content_disposition.lastIndexOf(".")).replace("\"", ""); // File saveDirFile = new File(savePath); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } // ?? if (!saveDirFile.canWrite()) { log.error("??"); throw new Exception(); } // System.out.println("------------------------------------------------"); // ? File file = new File(saveDirFile + "/" + fileName); FileOutputStream outStream = new FileOutputStream(file); int len = -1; byte[] b = new byte[1024]; while ((len = inputStream.read(b)) != -1) { outStream.write(b, 0, len); } outStream.flush(); outStream.close(); inputStream.close(); // ? localFile = fileName; } } catch (Exception e) { log.error("? !", e); } finally { } return localFile; }
From source file:com.cyphermessenger.client.SyncRequest.java
public static HttpURLConnection doRequest(String endpoint, CypherSession session, String[] keys, String[] values) throws IOException { HttpURLConnection connection = (java.net.HttpURLConnection) new URL(DOMAIN + endpoint).openConnection(); connection.setDoOutput(true);//from w w w . j a va2 s. c o m connection.setRequestMethod("POST"); connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); connection.connect(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); if (session != null) { writer.write("userID="); writer.write(session.getUser().getUserID() + "&sessionID="); writer.write(session.getSessionID()); } if (keys != null && keys.length > 0) { if (session != null) { writer.write('&'); } // write first row writer.write(keys[0]); writer.write('='); writer.write(URLEncoder.encode(values[0], "UTF-8")); for (int i = 1; i < keys.length; i++) { writer.write('&'); writer.write(keys[i]); writer.write('='); writer.write(URLEncoder.encode(values[i], "UTF-8")); } } writer.close(); return connection; }
From source file:com.francetelecom.clara.cloud.paas.it.services.helper.PaasServicesEnvApplicationAccessHelper.java
/** * Check if a string appear in the html page * * @param url// w w w . ja v a 2s . c o m * URL to test * @param token * String that must be in html page * @return Cookie that identifies the was or null if the test failed. An * empty string means that no cookie was found in the request, but * the check succeeded. */ private static String checkStringAndReturnCookie(URL url, String token, String httpProxyHost, int httpProxyPort) { InputStream is = null; String cookie = null; try { HttpURLConnection connection; if (httpProxyHost != null) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort)); connection = (HttpURLConnection) url.openConnection(proxy); } else { connection = (HttpURLConnection) url.openConnection(); } connection.setRequestMethod("GET"); is = connection.getInputStream(); // check http status code if (connection.getResponseCode() == 200) { DataInputStream dis = new DataInputStream(new BufferedInputStream(is)); StringWriter writer = new StringWriter(); IOUtils.copy(dis, writer, "UTF-8"); if (writer.toString().contains(token)) { cookie = connection.getHeaderField("Set-Cookie"); if (cookie == null) cookie = ""; } else { logger.info("URL " + url.getFile() + " returned code 200 but does not contain keyword '" + token + "'"); logger.debug("1000 first chars of response body: " + writer.toString().substring(0, 1000)); } } else { logger.error("URL " + url.getFile() + " returned code " + connection.getResponseCode() + " : " + connection.getResponseMessage()); if (System.getProperty("http.proxyHost") != null) { logger.info("Using proxy=" + System.getProperty("http.proxyHost") + ":" + System.getProperty("http.proxyPort")); } } } catch (IOException e) { logger.error("URL test failed: " + url.getFile() + " => " + e.getMessage() + " (" + e.getClass().getName() + ")"); if (System.getProperty("http.proxyHost") != null) { logger.info("Using proxy=" + System.getProperty("http.proxyHost") + ":" + System.getProperty("http.proxyPort")); } } finally { try { if (is != null) { is.close(); } } catch (IOException ioe) { // just going to ignore this one } } return cookie; }
From source file:BihuHttpUtil.java
/** * ??HTTPJSON?//from ww w. java 2 s .com * @param url * @param jsonStr */ public static String sendPostForJson(String url, String jsonStr) { StringBuffer sb = new StringBuffer(""); try { // URL realUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); connection.connect(); //POST DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(jsonStr.getBytes("UTF-8"));//??? out.flush(); out.close(); //?? BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String lines; while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); sb.append(lines); } reader.close(); // connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } return sb.toString(); }