List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:GoogleAPI.java
/** * Forms an HTTP request, sends it using GET method and returns the result of the request as a JSONObject. * /*from w w w . j a va 2 s . com*/ * @param url The URL to query for a JSONObject. * @return The translated String. * @throws Exception on error. */ protected static JSONObject retrieveJSON(final URL url) throws Exception { try { final HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setRequestProperty("referer", referrer); uc.setRequestMethod("GET"); uc.setDoOutput(true); try { final String result = inputStreamToString(uc.getInputStream()); return new JSONObject(result); } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html uc.getInputStream().close(); if (uc.getErrorStream() != null) { uc.getErrorStream().close(); } } } catch (Exception ex) { throw new Exception("[google-api-translate-java] Error retrieving translation.", ex); } }
From source file:Main.java
static String downloadUrl(String myurl) throws IOException { InputStream is = null;/*from www . ja v a 2s.c om*/ try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "Basic cm9vdDpvcmllbnRkYg=="); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); //start conn.connect(); int response = conn.getResponseCode(); Log.e("The response is: ", "" + response); is = conn.getInputStream(); //converte inputStream in stringa String contentAsString = readIt(is); return contentAsString; } catch (IOException e) { Log.e("HTTP", e.getMessage()); return null; } finally { if (is != null) { is.close(); } } }
From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java
public static String deleteServer(String host, String tenantId, String token, String serverId) throws IOException { String url = String.format("http://%s:8774/v2/%s/servers", host, tenantId); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("DELETE"); con.setRequestProperty("tenant_id", tenantId); con.setRequestProperty("server_id", serverId); String responseStr = sendDELETE(obj, con); System.out.println(responseStr); return responseStr; }
From source file:com.mopaas_mobile.http.BaseHttpRequester.java
public static String doPOST(String urlstr, List<BasicNameValuePair> params) throws IOException { String result = null;/*from w ww .ja v a2 s . c o m*/ URL url = new URL(urlstr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(false); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // connection.setRequestProperty("token",token); connection.setConnectTimeout(30000); connection.setReadTimeout(30000); connection.connect(); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); String content = ""; if (params != null && params.size() > 0) { for (int i = 0; i < params.size(); i++) { content = content + "&" + URLEncoder.encode(((NameValuePair) params.get(i)).getName(), "UTF-8") + "=" + URLEncoder.encode(((NameValuePair) params.get(i)).getValue(), "UTF-8"); } out.writeBytes(content.substring(1)); } out.flush(); out.close(); InputStream is = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer b = new StringBuffer(); int ch; while ((ch = br.read()) != -1) { b.append((char) ch); } result = b.toString().trim(); connection.disconnect(); return result; }
From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java
private static String sendPOST(URL url, HttpURLConnection con, String body) throws IOException { con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/json"); con.setRequestProperty("Accept", "application/json"); con.setDoOutput(true);/*from w w w . ja v a2s .c om*/ DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); logger.log(Level.INFO, "Sending POST request to URL : {0}", url); int responseCode = con.getResponseCode(); logger.log(Level.INFO, "Response Code : {0}", responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder responseStr = new StringBuilder(); while ((inputLine = in.readLine()) != null) { responseStr.append(inputLine); } in.close(); return responseStr.toString(); }
From source file:cc.vileda.sipgatesync.api.SipgateApi.java
public static String getToken(final String username, final String password) { try {/*from w ww . ja va2s . co m*/ final HttpURLConnection urlConnection = getConnection("/authorization/token"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestMethod("POST"); JSONObject request = new JSONObject(); request.put("username", username); request.put("password", password); OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream()); Log.d("SipgateApi", request.getString("username")); wr.write(request.toString()); wr.flush(); StringBuilder sb = new StringBuilder(); int HttpResult = urlConnection.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader( new InputStreamReader(urlConnection.getInputStream(), "utf-8")); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); Log.d("SipgateApi", "" + sb.toString()); final JSONObject response = new JSONObject(sb.toString()); return response.getString("token"); } else { System.out.println(urlConnection.getResponseMessage()); } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.meetingninja.csse.database.AgendaDatabaseAdapter.java
public static boolean deleteAgenda(String agendaID) throws IOException { // Server URL setup String _url = getBaseUri().appendPath(agendaID).build().toString(); // Establish connection URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.DELETE); addRequestHeader(conn, false);// www .j a va 2s .co m // Get server response 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 { Log.e(TAG, String.format("ErrorID: [%s] %s", tree.get(Keys.ERROR_ID).asText(), tree.get(Keys.ERROR_MESSAGE).asText())); } } conn.disconnect(); return result; }
From source file:com.mopaas_mobile.http.BaseHttpRequester.java
public static String doGETwithHeader(String urlstr, String token, List<BasicNameValuePair> params) throws IOException { String result = null;//from ww w . j a va 2 s. c om String content = ""; for (int i = 0; i < params.size(); i++) { content = content + "&" + URLEncoder.encode(((NameValuePair) params.get(i)).getName(), "UTF-8") + "=" + URLEncoder.encode(((NameValuePair) params.get(i)).getValue(), "UTF-8"); } URL url = new URL(urlstr + "?" + content.substring(1)); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("token", token); connection.setDoInput(true); connection.setRequestMethod("GET"); connection.setUseCaches(false); connection.connect(); InputStream is = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer b = new StringBuffer(); int ch; while ((ch = br.read()) != -1) { b.append((char) ch); } result = b.toString().trim(); connection.disconnect(); return result; }
From source file:io.github.retz.scheduler.MesosHTTPFetcher.java
static List<Map<String, Object>> fetchTasks(String master, String frameworkId, int offset, int limit) throws MalformedURLException { URL url = new URL("http://" + master + "/tasks?offset=" + offset + "&limit=" + limit); HttpURLConnection conn; try {//w w w . j a v a2 s. c o m conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); return parseTasks(conn.getInputStream(), frameworkId); } catch (IOException e) { return new LinkedList<>(); } }
From source file:GoogleAPI.java
/** * Forms an HTTP request, sends it using POST method and returns the result of the request as a JSONObject. * //from w w w .j ava 2 s . c om * @param url The URL to query for a JSONObject. * @param parameters Additional POST parameters * @return The translated String. * @throws Exception on error. */ protected static JSONObject retrieveJSON(final URL url, final String parameters) throws Exception { try { final HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setRequestProperty("referer", referrer); uc.setRequestMethod("POST"); uc.setDoOutput(true); final PrintWriter pw = new PrintWriter(uc.getOutputStream()); pw.write(parameters); pw.close(); uc.getOutputStream().close(); try { final String result = inputStreamToString(uc.getInputStream()); return new JSONObject(result); } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html if (uc.getInputStream() != null) { uc.getInputStream().close(); } if (uc.getErrorStream() != null) { uc.getErrorStream().close(); } if (pw != null) { pw.close(); } } } catch (Exception ex) { throw new Exception("[google-api-translate-java] Error retrieving translation.", ex); } }