List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:circleplus.app.http.AbstractHttpApi.java
protected BaseType executeHttpRequest(URL url, int method, JSONObject json, Parser<? extends BaseType> parser) throws IOException, Exception { InputStream is = null;/* w w w .j a va2 s. c o m*/ OutputStream os = null; HttpURLConnection conn = null; try { if (method == REQUEST_METHOD_POST && json != null) { conn = getHttpURLConnection(url, method, true); byte[] bytes = json.toString(0).getBytes(UTF8_CHARSET); os = conn.getOutputStream(); os.write(bytes); os.flush(); os.close(); } else { conn = getHttpURLConnection(url, method); } int response = conn.getResponseCode(); if (D) Log.d(TAG, "Response code = " + response); switch (response) { case 200: is = conn.getInputStream(); // TODO: calculate length String content = readStream(is, 2048 * 4); if (D) Log.d(TAG, content); return JSONUtils.consume(parser, content); // BAD REQUEST case 400: is = conn.getErrorStream(); String errorContent = readStream(is, 128); if (D) Log.d(TAG, "Http code: 400. Error message: " + errorContent); return JSONUtils.consume(new StatusParser(), errorContent); case 404: if (D) Log.d(TAG, "Http code: 404"); throw new IOException("Http code: 404"); case 500: if (D) Log.d(TAG, "Http code: 500"); throw new IOException("Http code: 500"); default: if (D) Log.d(TAG, "Default case for status code reached: " + response); throw new IOException("Http code: " + response); } } finally { if (conn != null) { conn.disconnect(); } if (is != null) { is.close(); } if (os != null) { os.close(); } } }
From source file:com.github.cambierr.jcollector.sender.OpenTsdbHttp.java
@Override public void send(ConcurrentLinkedQueue<Metric> _metrics) throws IOException { JSONArray entries = toJson(_metrics); if (entries.length() == 0) { return;// w ww . j a va2 s .c o m } HttpURLConnection conn = (HttpURLConnection) host.openConnection(); if (auth != null) { conn.setRequestProperty("Authorization", auth.getAuth()); } conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); OutputStream body = conn.getOutputStream(); body.write(entries.toString().getBytes()); body.flush(); if (conn.getResponseCode() >= 400) { BufferedReader responseBody = new BufferedReader(new InputStreamReader((conn.getErrorStream()))); String output; StringBuilder sb = new StringBuilder("Could not push data to OpenTSDB through ") .append(getClass().getSimpleName()).append("\n"); while ((output = responseBody.readLine()) != null) { sb.append(output).append("\n"); } Worker.logger.log(Level.WARNING, sb.toString()); throw new IOException(conn.getResponseMessage() + " (" + conn.getResponseCode() + ")"); } }
From source file:com.cd.reddit.http.RedditRequestor.java
public RedditRequestResponse executePost(RedditRequestInput input) throws RedditException { HttpURLConnection connection = getConnection(input); connection.setDoOutput(true);/* w w w.j av a2 s .c o m*/ try { connection.setRequestMethod("POST"); } catch (ProtocolException e) { throw new RedditException(e); } OutputStream outputStream = null; try { outputStream = connection.getOutputStream(); IOUtils.write(generateUrlEncodedForm(input.getFormParams()), outputStream, "UTF-8"); } catch (IOException e) { throw new RedditException(e); } finally { IOUtils.closeQuietly(outputStream); } return readResponse(connection, input); }
From source file:com.twotoasters.android.hoot.HootTransportHttpUrlConnection.java
private void setMultipartEntity(HootRequest request, HttpURLConnection connection) throws IOException { OutputStream os = null;//from www . j a va2 s. c om MultipartEntity entity = request.getMultipartEntity(); try { connection.setRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue()); os = new BufferedOutputStream(connection.getOutputStream(), (int) request.getMultipartEntity().getContentLength()); entity.writeTo(os); } finally { if (os != null) { try { os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); } } } }
From source file:de.openknowledge.jaxrs.versioning.AddressResourceTest.java
private InputStream send(URL url, String method, String resource) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true);/*from w w w . j a v a 2s . com*/ connection.setRequestMethod(method); connection.setRequestProperty("Content-Type", "application/json"); PrintWriter writer = new PrintWriter(connection.getOutputStream()); for (String line : IOUtils.readLines(AddressV1.class.getResourceAsStream(resource))) { writer.write(line); } writer.close(); return connection.getInputStream(); }
From source file:edu.illinois.cs.cogcomp.pipeline.server.ServerClientAnnotator.java
/** * The method is synchronized since the caching seems to have issues upon mult-threaded caching * @param overwrite if true, it would overwrite the values on cache *///from ww w. ja v a2 s. com public synchronized TextAnnotation annotate(String str, boolean overwrite) throws Exception { String viewsConnected = Arrays.toString(viewsToAdd); String views = viewsConnected.substring(1, viewsConnected.length() - 1).replace(" ", ""); ConcurrentMap<String, byte[]> concurrentMap = (db != null) ? db.hashMap(viewName, Serializer.STRING, Serializer.BYTE_ARRAY).createOrOpen() : null; String key = DigestUtils.sha1Hex(str + views); if (!overwrite && concurrentMap != null && concurrentMap.containsKey(key)) { byte[] taByte = concurrentMap.get(key); return SerializationHelper.deserializeTextAnnotationFromBytes(taByte); } else { URL obj = new URL(url + ":" + port + "/annotate"); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("charset", "utf-8"); con.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); con.setDoOutput(true); con.setUseCaches(false); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write("text=" + URLEncoder.encode(str, "UTF-8") + "&views=" + views); wr.flush(); InputStreamReader reader = new InputStreamReader(con.getInputStream()); BufferedReader in = new BufferedReader(reader); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); reader.close(); wr.close(); con.disconnect(); TextAnnotation ta = SerializationHelper.deserializeFromJson(response.toString()); if (concurrentMap != null) { concurrentMap.put(key, SerializationHelper.serializeTextAnnotationToBytes(ta)); this.db.commit(); } return ta; } }
From source file:com.iflytek.android.framework.volley.toolbox.HurlStack.java
@SuppressWarnings("deprecation") /* package */static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { VolleyLog.e("======setConnectionParametersForRequest:"); switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: // This is the deprecated way that needs to be handled for backwards // compatibility. // If the request's post body is null, then the assumption is that // the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { // Prepare output. There is no need to set Content-Length // explicitly, // since this is handled by HttpURLConnection using the size of // the prepared // output stream. connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(postBody);//from w w w.j a v a 2s .co m out.close(); } break; case Method.GET: // Not necessary to set the request method because connection // defaults to GET but // being explicit here. connection.setRequestMethod("GET"); break; case Method.DELETE: connection.setRequestMethod("DELETE"); break; case Method.POST: connection.setRequestMethod("POST"); addBodyIfExists(connection, request); break; case Method.PUT: connection.setRequestMethod("PUT"); addBodyIfExists(connection, request); break; case Method.HEAD: connection.setRequestMethod("HEAD"); break; case Method.OPTIONS: connection.setRequestMethod("OPTIONS"); break; case Method.TRACE: connection.setRequestMethod("TRACE"); break; case Method.PATCH: connection.setRequestMethod("PATCH"); addBodyIfExists(connection, request); break; default: throw new IllegalStateException("Unknown method type."); } }
From source file:com.ibm.iot.auto.bluemix.samples.ui.Connection.java
private HttpURLConnection createHttpURLPostConnection(String urlTail, JSONObject parameters) throws IOException, JSONException { URL url = new URL(apiBaseUrl + urlTail + "?tenant_id=" + tenantId); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestProperty("Authorization", "Basic " + authorizationValue); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); OutputStreamWriter connectionOutputStreamWriter = new OutputStreamWriter( httpURLConnection.getOutputStream()); parameters.write(connectionOutputStreamWriter); return httpURLConnection; }
From source file:com.daidiansha.acarry.control.network.core.volley.toolbox.HurlStack.java
@SuppressWarnings("deprecation") /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: // This is the deprecated way that needs to be handled for backwards // compatibility. // If the request's post body is null, then the assumption is that // the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { // Prepare output. There is no need to set Content-Length // explicitly, // since this is handled by HttpURLConnection using the size of // the prepared // output stream. connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(postBody);/*from w w w. jav a2 s . c o m*/ out.close(); } break; case Method.GET: // Not necessary to set the request method because connection // defaults to GET but // being explicit here. connection.setRequestMethod("GET"); break; case Method.DELETE: connection.setRequestMethod("DELETE"); break; case Method.POST: connection.setRequestMethod("POST"); addBodyIfExists(connection, request); break; case Method.PUT: connection.setRequestMethod("PUT"); addBodyIfExists(connection, request); break; case Method.HEAD: connection.setRequestMethod("HEAD"); break; case Method.OPTIONS: connection.setRequestMethod("OPTIONS"); break; case Method.TRACE: connection.setRequestMethod("TRACE"); break; case Method.PATCH: // connection.setRequestMethod("PATCH"); // If server doesnt support patch uncomment this connection.setRequestMethod("POST"); connection.setRequestProperty("X-HTTP-Method-Override", "PATCH"); addBodyIfExists(connection, request); break; default: throw new IllegalStateException("Unknown method type."); } }
From source file:MainFrame.CheckConnection.java
private boolean isOnline() throws MalformedURLException, IOException, Exception { String url = "http://www.itstepdeskview.hol.es"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", "Mozilla/5.0"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "apideskviewer.checkStatus={}"; // Send post request con.setDoOutput(true);//from w ww .ja v a 2 s.co m 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 : " + url); // System.out.println("Post parameters : " + urlParameters); // System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); JSONParser parser = new JSONParser(); Object parsedResponse = parser.parse(in); JSONObject jsonParsedResponse = (JSONObject) parsedResponse; String s = (String) jsonParsedResponse.get("response"); if (s.equals("online")) { return true; } else { return false; } }