List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java
public static List<Task> getTasks(String userID) throws JsonParseException, JsonMappingException, IOException { // Server URL setup String _url = getBaseUri().appendPath("Tasks").appendPath(userID).build().toString(); URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.GET); addRequestHeader(conn, false);/*w w w .ja v a2 s . c o m*/ // Get server response int responseCode = conn.getResponseCode(); String response = getServerResponse(conn); // Initialize ObjectMapper List<Task> taskList = new ArrayList<Task>(); final JsonNode taskArray = MAPPER.readTree(response).get(Keys.Task.LIST); if (taskArray.isArray()) { for (final JsonNode taskNode : taskArray) { Task t = TaskDatabaseAdapter.parseTasks(taskNode); if (t != null) { taskList.add(t); } } } else { Log.e(TAG, "Error parsing user's task list"); } conn.disconnect(); for (Task t : taskList) { TaskDatabaseAdapter.getTask(t); } return taskList; }
From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java
public static List<Note> getNotes(String userID) throws Exception { // Server URL setup String _url = getBaseUri().appendPath("Notes").appendPath(userID).build().toString(); Log.d("GETNOTES", _url); URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.GET); addRequestHeader(conn, false);/*w w w .j av a 2 s .c om*/ // Get server response int responseCode = conn.getResponseCode(); String response = getServerResponse(conn); // Initialize ObjectMapper List<Note> noteList = new ArrayList<Note>(); List<String> noteIds = new ArrayList<String>(); final JsonNode noteArray = MAPPER.readTree(response).get(Keys.Note.LIST); if (noteArray.isArray()) { for (final JsonNode noteNode : noteArray) { Note n = NotesDatabaseAdapter.getNote(JsonUtils.getJSONValue(noteNode, Keys.Note.ID)); n.setCreatedBy(JsonUtils.getJSONValue(noteNode, Keys.Note.CREATED_BY)); if (n != null) { noteList.add(n); } noteIds.add(noteNode.get(Keys.Note.ID).asText()); } } else { Log.e(TAG, "Error parsing user's notes list"); } conn.disconnect(); return noteList; }
From source file:net.drgnome.virtualpack.util.Util.java
public static boolean hasUpdate(int projectID, String version) { try {//from w w w . j av a 2s .c om HttpURLConnection con = (HttpURLConnection) (new URL( "https://api.curseforge.com/servermods/files?projectIds=" + projectID)).openConnection(); con.setConnectTimeout(5000); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; JVM)"); con.setRequestProperty("Pragma", "no-cache"); con.connect(); JSONArray json = (JSONArray) JSONValue.parse(new InputStreamReader(con.getInputStream())); String[] cdigits = ((String) ((JSONObject) json.get(json.size() - 1)).get("name")).toLowerCase() .split("\\."); String[] vdigits = version.toLowerCase().split("\\."); int max = vdigits.length > cdigits.length ? cdigits.length : vdigits.length; int a; int b; for (int i = 0; i < max; i++) { a = b = 0; try { a = Integer.parseInt(cdigits[i]); } catch (Exception e1) { char[] c = cdigits[i].toCharArray(); for (int j = 0; j < c.length; j++) { a += (c[j] << ((c.length - (j + 1)) * 8)); } } try { b = Integer.parseInt(vdigits[i]); } catch (Exception e1) { char[] c = vdigits[i].toCharArray(); for (int j = 0; j < c.length; j++) { b += (c[j] << ((c.length - (j + 1)) * 8)); } } if (a > b) { return true; } else if (a < b) { return false; } else if ((i == max - 1) && (cdigits.length > vdigits.length)) { return true; } } } catch (Exception e) { } return false; }
From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java
public static List<Group> getGroups(String userID) throws IOException { // Server URL setup System.out.println(userID);/* www . j a va 2 s . c o m*/ String _url = getBaseUri().appendPath("Groups").appendPath(userID).build().toString(); URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.GET); addRequestHeader(conn, false); // Get server response int responseCode = conn.getResponseCode(); String response = getServerResponse(conn); System.out.println("yes"); // Initialize ObjectMapper List<Group> groupList = new ArrayList<Group>(); List<String> groupIDList = new ArrayList<String>(); System.out.println("maybe"); final JsonNode groupArray = MAPPER.readTree(response).get(Keys.Group.LIST); System.out.println("no"); if (groupArray.isArray()) { for (final JsonNode groupNode : groupArray) { String _id = groupNode.get(Keys.Group.ID).asText(); System.out.println(_id); groupIDList.add(_id); } } conn.disconnect(); for (String id : groupIDList) { groupList.add(GroupDatabaseAdapter.getGroup(id)); } return groupList; }
From source file:com.heraldapp.share.facebook.Util.java
/** * Connect to an HTTP URL and return the response as a string. * //from w w w .j a v a 2 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); } String response = ""; HttpURLConnection conn = null; try { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); conn.setReadTimeout(10000); conn.setConnectTimeout(10000); 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")); } response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } catch (SocketTimeoutException e) { return response; } return response; }
From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java
public static List<Meeting> getMeetings(String userID) throws JsonParseException, JsonMappingException, IOException { // Server URL setup String _url = getBaseUri().appendPath("Meetings").appendPath(userID).build().toString(); // establish connection URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod("GET"); addRequestHeader(conn, false);/*from www . jav a 2 s . c o m*/ // Get server response int responseCode = conn.getResponseCode(); String response = getServerResponse(conn); // Initialize ObjectMapper List<Meeting> meetingsList = new ArrayList<Meeting>(); List<String> meetingIDList = new ArrayList<String>(); JsonNode responseNode = MAPPER.readTree(response); final JsonNode meetingsArray = responseNode.get(Keys.Meeting.LIST); if (meetingsArray != null && meetingsArray.isArray()) { for (final JsonNode meetingNode : meetingsArray) { String _id = meetingNode.get(Keys._ID).asText(); if (!meetingNode.get("type").asText().equals("MADE_MEETING")) { meetingIDList.add(_id); } } } else { logError(TAG, responseNode); } conn.disconnect(); for (String id : meetingIDList) { meetingsList.add(MeetingDatabaseAdapter.getMeetingInfo(id)); } return meetingsList; }
From source file:com.mobile.natal.natalchart.NetworkUtilities.java
/** * Sends a string via POST to a given url. * * @param context the context to use. * @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>. * @param readResponse if <code>true</code>, the response from the server is read and parsed as return message. * @return the response./*from w w w. java2s.co m*/ * @throws Exception if something goes wrong. */ public static String sendPost(Context context, String urlStr, String string, String user, String password, boolean readResponse) 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 && user.trim().length() > 0 && password.trim().length() > 0) { 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(); if (readResponse) { 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(); } else { return getMessageForCode(context, responseCode, context.getResources().getString(R.string.post_completed_properly)); } } catch (Exception e) { throw e; } finally { if (conn != null) conn.disconnect(); } }
From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java
/** * Does an HTTP post for a given form data string. * * @param data is the form data string.// w w w . j a v a 2 s . com * @param url is the url to post to. * @return the return string from the server. * @throws java.io.IOException */ public static String postData(String data, URL url) throws IOException { String result = null; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); try { HttpHelpers.addCommonHeaders(conn); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setConnectTimeout(HttpHelpers.NETWORK_TIMEOUT); conn.setReadTimeout(HttpHelpers.NETWORK_TIMEOUT); conn.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length)); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); writer.close(); String line; BufferedReader reader = (BufferedReader) getUncompressedResponseReader(conn); while ((line = reader.readLine()) != null) { if (result == null) result = line; else result += line; } reader.close(); } catch (IOException ex) { Log.e(TAG, "Failed to read stream data", ex); String error = null; // TODO Am not yet sure if the section below should make it in the production release. // I mainly use it to get details of a failed http request. I get a FileNotFoundException // when actually the url is correct but an exception was thrown at the server and i use this // to get the server call stack for debugging purposes. try { String line; BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream())); while ((line = reader.readLine()) != null) { if (error == null) error = line; else error += line; } reader.close(); } catch (Exception e) { Log.e(TAG, "Problem encountered while trying to get error information:" + error, ex); } } return result; }
From source file:net.ftb.util.DownloadUtils.java
/** * @param repoURL - URL on the repo// ww w.j av a 2s . com * @param fullDebug - should this dump the full cloudflare debug info in the console * @return boolean representing if the file exists */ public static boolean CloudFlareInspector(String repoURL, boolean fullDebug) { try { boolean ret; HttpURLConnection connection = (HttpURLConnection) new URL(repoURL + "cdn-cgi/trace").openConnection(); if (!fullDebug) connection.setRequestMethod("HEAD"); Logger.logInfo("CF-RAY: " + connection.getHeaderField("CF-RAY")); if (fullDebug) Logger.logInfo("CF Debug Info: " + connection.getContent().toString()); ret = connection.getResponseCode() == 200; IOUtils.close(connection); return ret; } catch (Exception e) { return false; } }
From source file:com.gmobi.poponews.util.HttpHelper.java
public static Response upload(String url, InputStream is) { Response response = new Response(); String boundary = Long.toHexString(System.currentTimeMillis()); HttpURLConnection connection = null; try {// www. jav a2 s . com URL httpURL = new URL(url); connection = (HttpURLConnection) httpURL.openConnection(); connection.setConnectTimeout(15000); connection.setReadTimeout(30000); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); byte[] st = ("--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"data\"\r\n" + "Content-Type: application/octet-stream; charset=UTF-8\r\n" + "Content-Transfer-Encoding: binary\r\n\r\n").getBytes(); byte[] en = ("\r\n--" + boundary + "--\r\n").getBytes(); connection.setRequestProperty("Content-Length", String.valueOf(st.length + en.length + is.available())); OutputStream os = connection.getOutputStream(); os.write(st); FileHelper.copy(is, os); os.write(en); os.flush(); os.close(); response.setStatusCode(connection.getResponseCode()); connection = null; } catch (Exception e) { Logger.error(e); } return response; }