List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:com.meetingninja.csse.database.NotesDatabaseAdapter.java
public static String createNote(Note n) throws Exception { // Server URL setup String _url = getBaseUri().build().toString(); // Establish connection URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.POST); //addRequestHeader(conn, true); // prepare POST payload ByteArrayOutputStream json = new ByteArrayOutputStream(); // this type of print stream allows us to get a string easily PrintStream ps = new PrintStream(json); // Create a generator to build the JSON string JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8); // Build JSON Object jgen.writeStartObject();// w w w . ja va 2 s. c o m jgen.writeStringField(Keys.Note.CREATED_BY, n.getCreatedBy()); jgen.writeStringField(Keys.Note.TITLE, n.getTitle()); jgen.writeStringField(Keys.Note.DESC, n.getDescription()); jgen.writeStringField(Keys.Note.CONTENT, n.getContent()); jgen.writeStringField(Keys.Note.UPDATED, n.getDateCreated()); jgen.writeEndObject(); jgen.close(); // Get JSON Object payload from print stream String payload = json.toString("UTF8"); Log.d("CREATENOTE_payload", payload); ps.close(); // Send payload int responseCode = sendPostPayload(conn, payload); String response = getServerResponse(conn); Log.d("CREATENOTE_response", response); String ID = ""; if (!response.isEmpty()) { JsonNode tree = MAPPER.readTree(response); if (!tree.has(Keys.Note.ID)) ID = "-1"; else ID = tree.get(Keys.Note.ID).asText(); } conn.disconnect(); return ID; }
From source file:Main.java
public static String upLoad(File file, String RequestURL) { String BOUNDER = UUID.randomUUID().toString(); String PREFIX = "--"; String END = "/r/n"; try {/*from w ww .ja v a2 s . co m*/ URL url = new URL(RequestURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(TIME_OUT); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Charset", CHARSET); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Cotent-Type", CONTENT_TYPE + ";boundary=" + BOUNDER); if (file != null) { OutputStream outputStream = connection.getOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream(outputStream); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDER + END); dataOutputStream.write(sb.toString().getBytes()); InputStream in = new FileInputStream(file); byte[] b = new byte[1024]; int l = 0; while ((l = in.read()) != -1) { outputStream.write(b, 0, l); } in.close(); dataOutputStream.write(END.getBytes()); dataOutputStream.write((PREFIX + BOUNDER + PREFIX + END).getBytes()); dataOutputStream.flush(); int i = connection.getResponseCode(); if (i == 200) { return SUCCESS; } } } catch (IOException e) { e.printStackTrace(); } return FALIURE; }
From source file:core.Utility.java
public static ArrayList<String> getWikiText(String _word) throws MalformedURLException, IOException { ArrayList<String> _list = new ArrayList(); try {// www . j a v a 2 s . com URL url = new URL("http://en.wiktionary.org/w/api.php" + "?action=parse" + "&prop=wikitext" + "&page=" + _word + "&format=xmlfm"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output, wikiText = ""; while ((output = br.readLine()) != null) { wikiText += output + "\n"; } conn.disconnect(); } catch (MalformedURLException e) { throw e; } catch (IOException e) { throw e; } return _list; }
From source file:com.meetingninja.csse.database.MeetingDatabaseAdapter.java
public static Meeting createMeeting(String userID, Meeting m) throws IOException, MalformedURLException { // Server URL setup String _url = getBaseUri().appendPath(userID).build().toString(); // establish connection URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); addRequestHeader(conn, true);/*from w w w .j ava 2s .co m*/ // prepare POST payload ByteArrayOutputStream json = new ByteArrayOutputStream(); // this type of print stream allows us to get a string easily PrintStream ps = new PrintStream(json); // Create a generator to build the JSON string JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8); // Build JSON Object jgen.writeStartObject(); jgen.writeStringField(Keys.User.ID, userID); jgen.writeStringField(Keys.Meeting.TITLE, m.getTitle()); jgen.writeStringField(Keys.Meeting.LOCATION, m.getLocation()); jgen.writeStringField(Keys.Meeting.DATETIME, m.getStartTime()); jgen.writeStringField(Keys.Meeting.OTHEREND, m.getEndTime()); jgen.writeStringField(Keys.Meeting.DESC, m.getDescription()); jgen.writeArrayFieldStart(Keys.Meeting.ATTEND); // TODO: Add attendees to meeting // for (String attendee : m.getAttendance()) { // if (attendee.isAttending()) { jgen.writeStartObject(); jgen.writeStringField(Keys.User.ID, userID); jgen.writeEndObject(); // } // } jgen.writeEndArray(); jgen.writeEndObject(); jgen.close(); // Get JSON Object payload from print stream String payload = json.toString("UTF8"); ps.close(); // send payload int responseCode = sendPostPayload(conn, payload); String response = getServerResponse(conn); // prepare to get the id of the created Meeting JsonNode responseMap; m.setID(404); Meeting created = new Meeting(m); /* * result should get valid={"meetingID":"##"} */ // String result = new String(); if (!response.isEmpty()) { responseMap = MAPPER.readTree(response); if (responseMap.has(Keys.Meeting.ID)) created.setID(responseMap.get(Keys.Meeting.ID).asText()); } // if (!result.equalsIgnoreCase("invalid")) // created.setID(result); conn.disconnect(); return created; }
From source file:com.gmt2001.HttpRequest.java
public static HttpResponse getData(RequestType type, String url, String post, HashMap<String, String> headers) { Thread.setDefaultUncaughtExceptionHandler(com.gmt2001.UncaughtExceptionHandler.instance()); HttpResponse r = new HttpResponse(); r.type = type;/* w w w .j a v a 2 s . c o m*/ r.url = url; r.post = post; r.headers = headers; try { URL u = new URL(url); HttpURLConnection h = (HttpURLConnection) u.openConnection(); for (Entry<String, String> e : headers.entrySet()) { h.addRequestProperty(e.getKey(), e.getValue()); } h.setRequestMethod(type.name()); h.setUseCaches(false); h.setDefaultUseCaches(false); h.setConnectTimeout(timeout); h.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015"); if (!post.isEmpty()) { h.setDoOutput(true); } h.connect(); if (!post.isEmpty()) { BufferedOutputStream stream = new BufferedOutputStream(h.getOutputStream()); stream.write(post.getBytes()); stream.flush(); stream.close(); } if (h.getResponseCode() < 400) { r.content = IOUtils.toString(new BufferedInputStream(h.getInputStream()), h.getContentEncoding()); r.httpCode = h.getResponseCode(); r.success = true; } else { r.content = IOUtils.toString(new BufferedInputStream(h.getErrorStream()), h.getContentEncoding()); r.httpCode = h.getResponseCode(); r.success = false; } } catch (IOException ex) { r.success = false; r.httpCode = 0; r.exception = ex.getMessage(); com.gmt2001.Console.err.printStackTrace(ex); } return r; }
From source file:Main.java
public static String openUrl(String url, String method, Bundle params) { if (method.equals("GET")) { url = url + "?" + encodeUrl(params); }/*from w w w . j a v a2 s .co m*/ String response = ""; try { Log.d(LOG_TAG, method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " RenrenAndroidSDK"); if (!method.equals("GET")) { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8")); } response = read(conn.getInputStream()); } catch (Exception e) { Log.e(LOG_TAG, e.getMessage()); throw new RuntimeException(e.getMessage(), e); } return response; }
From source file:com.meetingninja.csse.database.TaskDatabaseAdapter.java
public static Boolean deleteTask(String taskID) throws IOException { String _url = getBaseUri().appendPath(taskID).build().toString(); URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.DELETE); addRequestHeader(conn, false);/*from www. j a v a2 s . c om*/ 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(); return result; }
From source file:ca.xecure.easychip.CommonUtilities.java
public static void http_post(String endpoint, Map<String, String> params) throws IOException { URL url;//from w w w .jav a 2 s . co m try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } String body = JSONValue.toJSONString(params); Log.v(LOG_TAG, "Posting '" + body + "' to " + url); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } }
From source file:com.adr.raspberryleds.HTTPUtils.java
public static JSONObject execPOST(String address, JSONObject params) throws IOException { BufferedReader readerin = null; Writer writerout = null;//from w w w. j av a 2 s . c o m try { URL url = new URL(address); String query = params.toString(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(10000 /* milliseconds */); connection.setConnectTimeout(15000 /* milliseconds */); connection.setRequestMethod("POST"); connection.setAllowUserInteraction(false); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.addRequestProperty("Content-Type", "application/json,encoding=UTF-8"); connection.addRequestProperty("Content-length", String.valueOf(query.length())); writerout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); writerout.write(query); writerout.flush(); writerout.close(); writerout = null; int responsecode = connection.getResponseCode(); if (responsecode == HttpURLConnection.HTTP_OK) { StringBuilder text = new StringBuilder(); readerin = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String line = null; while ((line = readerin.readLine()) != null) { text.append(line); text.append(System.getProperty("line.separator")); } JSONObject result = new JSONObject(text.toString()); if (result.has("exception")) { throw new IOException( MessageFormat.format("Remote exception: {0}.", result.getString("exception"))); } else { return result; } } else { throw new IOException(MessageFormat.format("HTTP response error: {0}. {1}", Integer.toString(responsecode), connection.getResponseMessage())); } } catch (JSONException ex) { throw new IOException(MessageFormat.format("Parse exception: {0}.", ex.getMessage())); } finally { if (writerout != null) { writerout.close(); writerout = null; } if (readerin != null) { readerin.close(); readerin = null; } } }
From source file:Main.java
private static HttpURLConnection initHttpURLConn(String requestURL) throws MalformedURLException, IOException, ProtocolException { URL url = new URL(requestURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(TIME_OUT); connection.setReadTimeout(TIME_OUT); connection.setDoInput(true);//from www . j a v a 2s . c o m connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Charset", CHARSET); connection.setRequestProperty("connection", "keep-alive"); return connection; }