List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:ilearnrw.utils.ServerHelperClass.java
public static String sendGet(String link) throws Exception { String url = baseUrl + link;/*w w w . j a va 2s .com*/ URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); con.setRequestProperty("Authorization", userNamePasswordBase64("api", "api")); //con.setRequestProperty("User-Agent", USER_AGENT); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); }
From source file:localSPs.SpiderOakAPI.java
public static String connectWithREST(String url, String method) throws IOException, ProtocolException, MalformedURLException { String newURL = ""; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // Connect with a REST Method: GET, DELETE, PUT con.setRequestMethod(method); //add request header con.setReadTimeout(20000);/*from ww w . j a v a 2 s . c o m*/ con.setConnectTimeout(20000); con.setRequestProperty("User-Agent", "Mozilla/5.0"); if (method.equals(DELETE) || method.equals(PUT)) con.addRequestProperty("Authorization", "Base M5XWW5JNONZWUMSANBXXI3LBNFWC4Y3PNU5E2NDSNFXTEMZVJ5QWW"); int responseCode = con.getResponseCode(); // Read response BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); newURL = response.toString(); return newURL; }
From source file:com.meetingninja.csse.database.ContactDatabaseAdapter.java
public static List<Contact> deleteContact(String relationID) throws IOException { String _url = getBaseUri().appendPath("Relations").appendPath(relationID).build().toString(); URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(IRequest.DELETE); addRequestHeader(conn, false);/*ww w . j a v a 2 s. c o 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(TAG, tree); } } conn.disconnect(); SessionManager session = SessionManager.getInstance(); List<Contact> contacts = getContacts(session.getUserID()); return contacts; }
From source file:com.hichinaschool.flashcards.anki.web.HttpFetcher.java
public static String downloadFileToSdCardMethod(String UrlToFile, Context context, String prefix, String method) {//from w ww.j a va 2 s .c o m try { URL url = new URL(UrlToFile); String extension = UrlToFile.substring(UrlToFile.length() - 4); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod(method); urlConnection.setRequestProperty("Referer", "com.hichinaschool.flashcards.anki"); urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) "); urlConnection.setRequestProperty("Accept", "*/*"); urlConnection.connect(); File file = File.createTempFile(prefix, extension, DiskUtil.getStoringDirectory()); FileOutputStream fileOutput = new FileOutputStream(file); InputStream inputStream = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int bufferLength = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); } fileOutput.close(); return file.getAbsolutePath(); } catch (Exception e) { return "FAILED " + e.getMessage(); } }
From source file:Main.java
static String validGet(URL url) throws IOException { String html = ""; HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER; HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); // TODO ensure HttpsURLConnection.setDefaultSSLSocketFactory isn't // required to be reset like hostnames are HttpURLConnection conn = null; try {//from ww w. j a va 2 s . co m conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setRequestMethod("GET"); setBasicAuthentication(conn, url); int status = conn.getResponseCode(); if (status != 200) { Logd(TAG, "Failed to get from server, returned code: " + status); throw new IOException("Get failed with error code " + status); } else { InputStreamReader in = new InputStreamReader(conn.getInputStream()); BufferedReader br = new BufferedReader(in); String decodedString; while ((decodedString = br.readLine()) != null) { html += decodedString; } in.close(); } } catch (IOException e) { Logd(TAG, "Failed to get from server: " + e.getMessage()); } if (conn != null) { conn.disconnect(); } return html; }
From source file:fr.haploid.webservices.WebServicesHelper.java
protected static synchronized WebServicesResponseData downloadFromServer(String url, JSONObject params, String type) {/*from w ww .j a va2 s . c o m*/ int responseCode = 9999; StringBuffer buffer = new StringBuffer(); Uri.Builder builder = new Uri.Builder(); builder.encodedPath(url); JSONArray namesOfParams = params.names(); for (int i = 0; i < namesOfParams.length(); i++) { try { String param = namesOfParams.getString(i); builder.appendQueryParameter(param, params.get(param).toString()); } catch (JSONException e) { return new WebServicesResponseData("JSONException " + e.toString(), responseCode, false); } } URL urlBuild; try { urlBuild = new URL(builder.build().toString()); } catch (MalformedURLException e) { return new WebServicesResponseData("MalformedURLException " + e.toString(), responseCode, false); } try { HttpURLConnection urlConnection = (HttpURLConnection) urlBuild.openConnection(); try { urlConnection.setRequestMethod(type); } catch (ProtocolException e) { return new WebServicesResponseData("ProtocolException " + e.toString(), responseCode, false); } urlConnection.connect(); responseCode = urlConnection.getResponseCode(); if (responseCode < 400) { InputStream inputStream = urlConnection.getInputStream(); if (inputStream == null) { return new WebServicesResponseData(null, responseCode, false); } BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line + "\n"); } if (buffer.length() == 0) { return new WebServicesResponseData(null, responseCode, false); } } } catch (IOException e) { return new WebServicesResponseData("IOException " + e.toString(), responseCode, false); } return new WebServicesResponseData(buffer.toString(), responseCode, true); }
From source file:software.uncharted.util.HTTPUtil.java
public static String post(String urlToRead, String postData) { URL url;/* ww w .ja v a2s . c o m*/ HttpURLConnection conn; try { url = new URL(urlToRead); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json"); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(postData); wr.flush(); wr.close(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; InputStream is = conn.getInputStream(); while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); return buffer.toString(); } catch (Exception e) { e.printStackTrace(); System.err.println("Failed to read URL: " + urlToRead + " <" + e.getMessage() + ">"); } return null; }
From source file:com.meetingninja.csse.database.GroupDatabaseAdapter.java
private static String sendSingleEdit(String payload) throws IOException { String _url = getBaseUri().build().toString(); URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(IRequest.PUT); addRequestHeader(conn, false);//from w w w.ja v a 2 s .c o m sendPostPayload(conn, payload); return getServerResponse(conn); }
From source file:website.openeng.anki.web.HttpFetcher.java
public static String downloadFileToSdCardMethod(String UrlToFile, Context context, String prefix, String method) {/* w w w.j a v a 2 s . co m*/ try { URL url = new URL(UrlToFile); String extension = UrlToFile.substring(UrlToFile.length() - 4); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod(method); urlConnection.setRequestProperty("Referer", "website.openeng.anki"); urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) "); urlConnection.setRequestProperty("Accept", "*/*"); urlConnection.setConnectTimeout(10000); urlConnection.setReadTimeout(60000); urlConnection.connect(); File file = File.createTempFile(prefix, extension, context.getCacheDir()); FileOutputStream fileOutput = new FileOutputStream(file); InputStream inputStream = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int bufferLength = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); } fileOutput.close(); return file.getAbsolutePath(); } catch (Exception e) { return "FAILED " + e.getMessage(); } }
From source file:com.michelin.cio.hudson.plugins.qc.QualityCenterUtils.java
/** * Checks the Quality Center server URL. */// ww w . j a va 2 s . com public static FormValidation checkQcServerURL(String value, Boolean acceptEmpty) { String url; // Path to the page to check if the server is alive String page = "servlet/tdservlet/TDAPI_GeneralWebTreatment"; // Do will allow empty value? if (StringUtils.isBlank(value)) { if (!acceptEmpty) { return FormValidation.error(Messages.QualityCenter_ServerURLMustBeDefined()); } else { return FormValidation.ok(); } } // Does the URL ends with a "/" ? if not, add it if (value.lastIndexOf("/") == value.length() - 1) { url = value + page; } else { url = value + "/" + page; } // Open the connection and perform a HEAD request HttpURLConnection connection; try { connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("HEAD"); // Check the response code if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { return FormValidation.error(connection.getResponseMessage()); } } catch (MalformedURLException ex) { // This is not a valid URL return FormValidation.error(Messages.QualityCenter_MalformedServerURL()); } catch (IOException ex) { // Cant open connection to the server return FormValidation.error(Messages.QualityCenter_ErrorOpeningServerConnection()); } return FormValidation.ok(); }