List of usage examples for java.net HttpURLConnection setDoInput
public void setDoInput(boolean doinput)
From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java
@Override public byte[] post(String url, byte[] data) throws IOException { // Build and connect HttpURLConnection connection = buildConnection(url); connection.setDoOutput(true);/*from w w w . j av a2s. co m*/ connection.setDoInput(true); connection.connect(); // Send the request connection.getOutputStream().write(data); connection.getOutputStream().flush(); connection.getOutputStream().close(); // Check for errors checkForErrors(connection); // Get the result return disconnectAndReturn(connection, IOUtils.toByteArray(connection.getInputStream())); }
From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java
@Override public String postString(String url, String data) throws IOException { // Build and connect HttpURLConnection connection = buildConnection(url); connection.setDoOutput(true);/*from ww w . j a v a 2 s . co m*/ connection.setDoInput(true); connection.connect(); // Send the request connection.getOutputStream().write(data.getBytes("ISO-8859-1")); connection.getOutputStream().flush(); connection.getOutputStream().close(); // Check for errors checkForErrors(connection); // Get the result return disconnectAndReturn(connection, IOUtils.toString(connection.getInputStream(), "ISO-8859-1")); }
From source file:com.github.hipchat.api.Room.java
public List<HistoryMessage> getHistory(Date date) { HipChat hc = getOrigin();// ww w. j a v a 2 s . c o m Calendar c = Calendar.getInstance(); String dateString = null; String tzString = null; if (date != null) { c.setTime(date); TimeZone tz = c.getTimeZone(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); dateString = sdf.format(date); tzString = tz.getDisplayName(tz.inDaylightTime(date), TimeZone.SHORT); } else { Date tDate = new Date(); c.setTime(tDate); TimeZone tz = c.getTimeZone(); dateString = "recent"; tzString = tz.getDisplayName(tz.inDaylightTime(tDate), TimeZone.SHORT); } String query = String.format(HipChatConstants.ROOMS_HISTORY_QUERY_FORMAT, getId(), dateString, tzString, HipChatConstants.JSON_FORMAT, hc.getAuthToken()); OutputStream output = null; InputStream input = null; HttpURLConnection connection = null; List<HistoryMessage> messages = null; try { URL requestUrl = new URL(HipChatConstants.API_BASE + HipChatConstants.ROOMS_HISTORY + query); connection = (HttpURLConnection) requestUrl.openConnection(); connection.setDoInput(true); input = connection.getInputStream(); messages = MessageParser.parseRoomHistory(this, input); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(output); connection.disconnect(); } return messages; }
From source file:edu.pdx.cecs.orcycle.NoteUploader.java
boolean uploadOneNote(long noteId) { boolean result = false; final String postUrl = mCtx.getResources().getString(R.string.post_url); try {//w w w.j a va 2 s .co m JSONArray jsonNoteResponses = getNoteResponsesJSON(noteId); URL url = new URL(postUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); conn.setRequestProperty("Cycleatl-Protocol-Version", "4"); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); JSONObject jsonNote; if (null != (jsonNote = getNoteJSON(noteId))) { try { String deviceId = userId; dos.writeBytes(notesep + ContentField("note") + jsonNote.toString() + "\r\n"); dos.writeBytes( notesep + ContentField("version") + String.valueOf(kSaveNoteProtocolVersion) + "\r\n"); dos.writeBytes(notesep + ContentField("device") + deviceId + "\r\n"); dos.writeBytes(notesep + ContentField("noteResponses") + jsonNoteResponses.toString() + "\r\n"); if (null != imageData) { dos.writeBytes(notesep + "Content-Disposition: form-data; name=\"file\"; filename=\"" + deviceId + ".jpg\"\r\n" + "Content-Type: image/jpeg\r\n\r\n"); dos.write(imageData); dos.writeBytes("\r\n"); } dos.writeBytes(notesep); dos.flush(); } catch (Exception ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } finally { dos.close(); } int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); // JSONObject responseData = new JSONObject(serverResponseMessage); Log.v("Jason", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 201 || serverResponseCode == 202) { mDb.open(); mDb.updateNoteStatus(noteId, NoteData.STATUS_SENT); mDb.close(); result = true; } } else { result = false; } } catch (IllegalStateException ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } catch (IOException ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } catch (JSONException ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } finally { NoteUploader.setPending(noteId, false); } return result; }
From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java
@Override public JSOG postJsog(String url, JSOG data) throws IOException { // Build and connect HttpURLConnection connection = buildConnection(url); connection.setDoOutput(true);/* w ww. j a v a2s .c o m*/ connection.setDoInput(true); connection.setRequestProperty("Content-Type", "application/json; charset=ISO-8859-1"); connection.connect(); // Send the request connection.getOutputStream().write(data.toString().getBytes("ISO-8859-1")); connection.getOutputStream().flush(); connection.getOutputStream().close(); // Check for errors checkForErrors(connection); // Get the result return disconnectAndReturn(connection, JSOG.parse(IOUtils.toString(connection.getInputStream(), "ISO-8859-1"))); }
From source file:io.confluent.kafkarest.tools.ProducerPerformance.java
@Override protected void doIteration(PerformanceStats.Callback cb) { HttpURLConnection connection = null; try {//from w w w. jav a 2 s . c om URL url = new URL(targetUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", Versions.KAFKA_MOST_SPECIFIC_DEFAULT); connection.setRequestProperty("Content-Length", requestEntityLength); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); OutputStream os = connection.getOutputStream(); os.write(requestEntity); os.flush(); os.close(); int responseStatus = connection.getResponseCode(); if (responseStatus >= 400) { InputStream es = connection.getErrorStream(); ErrorMessage errorMessage = jsonDeserializer.readValue(es, ErrorMessage.class); es.close(); throw new RuntimeException(String.format("Unexpected HTTP error status %d: %s", responseStatus, errorMessage.getMessage())); } InputStream is = connection.getInputStream(); while (is.read(buffer) > 0) { // Ignore output, just make sure we actually receive it } is.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } cb.onCompletion(recordsPerIteration, bytesPerIteration); }
From source file:com.apache.ivy.BasicURLHandler.java
public InputStream openStreamPost(URL url, ArrayList<NameValuePair> postData) throws IOException { // Install the IvyAuthenticator if ("http".equals(url.getProtocol()) || "https".equals(url.getProtocol())) { IvyAuthenticator.install();//w w w . ja va2s. c o m } URLConnection conn = null; try { url = normalizeToURL(url); conn = url.openConnection(); conn.setRequestProperty("User-Agent", "Apache Ivy/1.0");// + Ivy.getIvyVersion()); conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); if (conn instanceof HttpURLConnection) { HttpURLConnection httpCon = (HttpURLConnection) conn; httpCon.setRequestMethod("POST"); httpCon.setDoInput(true); httpCon.setDoOutput(true); byte[] postDataBytes = getQuery(postData).getBytes(Charset.forName("UTF-8")); String contentLength = String.valueOf(postDataBytes.length); httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpCon.setRequestProperty("Content-Length", contentLength); httpCon.setDoOutput(true); httpCon.connect(); httpCon.getOutputStream().write(postDataBytes); conn.getOutputStream().flush(); if (!checkStatusCode(url, httpCon)) { throw new IOException("The HTTP response code for " + url + " did not indicate a success." + " See log for more detail."); } } // read the output InputStream inStream = getDecodingInputStream(conn.getContentEncoding(), conn.getInputStream()); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = inStream.read(buffer)) > 0) { outStream.write(buffer, 0, len); } return new ByteArrayInputStream(outStream.toByteArray()); } finally { disconnect(conn); } }
From source file:org.scigap.iucig.controller.ScienceDisciplineController.java
@ResponseBody @RequestMapping(value = "/updateScienceDiscipline", method = RequestMethod.POST) public void updateScienceDiscipline(@RequestBody ScienceDiscipline discipline, HttpServletRequest request) throws Exception { try {/*from ww w . jav a2 s . c om*/ String remoteUser; if (request != null) { remoteUser = request.getRemoteUser(); } else { throw new Exception("Remote user is null"); } int primarySubDisId = 0; int secondarySubDisId = 0; int tertiarySubDisId = 0; String urlParameters = "user=" + remoteUser; if (discipline != null) { Map<String, String> primarySubDisc = discipline.getPrimarySubDisc(); if (primarySubDisc != null && !primarySubDisc.isEmpty()) { for (String key : primarySubDisc.keySet()) { if (key.equals("id")) { primarySubDisId = Integer.valueOf(primarySubDisc.get(key)); urlParameters += "&discipline1=" + primarySubDisId; } } } else { Map<String, Object> primaryDiscipline = discipline.getPrimaryDisc(); if (primaryDiscipline != null && !primaryDiscipline.isEmpty()) { Object subdisciplines = primaryDiscipline.get("subdisciplines"); if (subdisciplines instanceof ArrayList) { for (int i = 0; i < ((ArrayList) subdisciplines).size(); i++) { Object disc = ((ArrayList) subdisciplines).get(i); if (disc instanceof HashMap) { if (((HashMap) disc).get("name").equals("Other / Unspecified")) { primarySubDisId = Integer.valueOf((((HashMap) disc).get("id")).toString()); } } } urlParameters += "&discipline1=" + primarySubDisId; } } } Map<String, String> secondarySubDisc = discipline.getSecondarySubDisc(); if (secondarySubDisc != null && !secondarySubDisc.isEmpty()) { for (String key : secondarySubDisc.keySet()) { if (key.equals("id")) { secondarySubDisId = Integer.valueOf(secondarySubDisc.get(key)); urlParameters += "&discipline2=" + secondarySubDisId; } } } else { Map<String, Object> secondaryDisc = discipline.getSecondaryDisc(); if (secondaryDisc != null && !secondaryDisc.isEmpty()) { Object subdisciplines = secondaryDisc.get("subdisciplines"); if (subdisciplines instanceof ArrayList) { for (int i = 0; i < ((ArrayList) subdisciplines).size(); i++) { Object disc = ((ArrayList) subdisciplines).get(i); if (disc instanceof HashMap) { if (((HashMap) disc).get("name").equals("Other / Unspecified")) { secondarySubDisId = Integer .valueOf((((HashMap) disc).get("id")).toString()); } } } urlParameters += "&discipline2=" + secondarySubDisId; } } } Map<String, String> tertiarySubDisc = discipline.getTertiarySubDisc(); if (tertiarySubDisc != null && !tertiarySubDisc.isEmpty()) { for (String key : tertiarySubDisc.keySet()) { if (key.equals("id")) { tertiarySubDisId = Integer.valueOf(tertiarySubDisc.get(key)); urlParameters += "&discipline3=" + tertiarySubDisId; } } } else { Map<String, Object> tertiaryDisc = discipline.getTertiaryDisc(); if (tertiaryDisc != null && !tertiaryDisc.isEmpty()) { Object subdisciplines = tertiaryDisc.get("subdisciplines"); if (subdisciplines instanceof ArrayList) { for (int i = 0; i < ((ArrayList) subdisciplines).size(); i++) { Object disc = ((ArrayList) subdisciplines).get(i); if (disc instanceof HashMap) { if (((HashMap) disc).get("name").equals("Other / Unspecified")) { tertiarySubDisId = Integer.valueOf((((HashMap) disc).get("id")).toString()); } } } urlParameters += "&discipline3=" + tertiarySubDisId; } } } URL obj = new URL(SCIENCE_DISCIPLINE_URL + "discipline/"); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); urlParameters += "&date=" + discipline.getDate() + "&source=cybergateway&commit=Update&cluster=" + discipline.getCluster(); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + SCIENCE_DISCIPLINE_URL); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.chainsaw.clearweather.BackgroundFetch.java
@Override protected WeatherData doInBackground(String... params) { publishProgress(10);/*from w ww . j a v a2s . c om*/ HttpURLConnection con = null; InputStream is = null; if (!isNetworkAvailable()) { fetchStatus = NO_NETWORK; } if (isNetworkAvailable()) { try { con = (HttpURLConnection) (new URL(params[0])).openConnection(); con.setRequestMethod("GET"); con.setDoInput(true); con.setDoOutput(true); con.setConnectTimeout(SERVER_TIMEOUT); con.connect(); buffer = new StringBuffer(); is = con.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line = null; while ((line = br.readLine()) != null) buffer.append(line); is.close(); con.disconnect(); } catch (Throwable t) { fetchStatus = SERVER_ERROR; t.printStackTrace(); } finally { try { is.close(); } catch (Throwable t) { fetchStatus = SERVER_ERROR; t.printStackTrace(); } try { con.disconnect(); } catch (Throwable t) { fetchStatus = SERVER_ERROR; t.printStackTrace(); } } try { weatherData = (buffer.toString() == null) ? new JSONObject() : new JSONObject(buffer.toString()); fetchStatus = DONE; } catch (Throwable e) { fetchStatus = NO_DATA; e.printStackTrace(); } is = null; con = null; try { if ((fetchStatus == DONE) && (weatherData != null)) { WeatherData.newDataStatus = DONE; JSONObject mainObj = weatherData.getJSONObject("main"); JSONArray weatherObj = weatherData.getJSONArray("weather"); returnData = new WeatherData(true, (int) (Math.round(mainObj.getDouble("temp") - 273.15)), ((int) (Math.round(mainObj.getInt("humidity")))), weatherData.getString("name"), ((JSONObject) weatherObj.get(0)).getString("description")); } } catch (Throwable e) { fetchStatus = NO_DATA; e.printStackTrace(); } } switch (fetchStatus) { case NO_DATA: WeatherData.newDataStatus = NO_DATA; break; case SERVER_ERROR: WeatherData.newDataStatus = SERVER_ERROR; break; case NO_NETWORK: WeatherData.newDataStatus = NO_NETWORK; break; } if (returnData == null) WeatherData.newDataStatus = NO_DATA; return returnData; }
From source file:io.undertow.servlet.test.streams.ServletInputStreamTestCase.java
private void runTestViaJavaImpl(final String message, String url) throws IOException { HttpURLConnection urlcon = null; try {//from w w w.j a v a 2 s . c o m String uri = DefaultServer.getDefaultServerURL() + "/servletContext/" + url; urlcon = (HttpURLConnection) new URL(uri).openConnection(); urlcon.setInstanceFollowRedirects(true); urlcon.setRequestProperty("Connection", "close"); urlcon.setRequestMethod("POST"); urlcon.setDoInput(true); urlcon.setDoOutput(true); OutputStream os = urlcon.getOutputStream(); os.write(message.getBytes()); os.close(); Assert.assertEquals(StatusCodes.OK, urlcon.getResponseCode()); InputStream is = urlcon.getInputStream(); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); byte[] buf = new byte[256]; int len; while ((len = is.read(buf)) > 0) { bytes.write(buf, 0, len); } is.close(); final String response = new String(bytes.toByteArray(), 0, bytes.size()); if (!message.equals(response)) { System.out.println(String.format("response=%s", Hex.encodeHexString(response.getBytes()))); } Assert.assertEquals(message, response); } finally { if (urlcon != null) { urlcon.disconnect(); } } }