List of usage examples for java.net HttpURLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:com.juick.android.Utils.java
public static RESTResponse postForm(final Context context, final String url, ArrayList<NameValuePair> data) { try {/*from w ww. j a v a 2 s. com*/ final String end = "\r\n"; final String twoHyphens = "--"; final String boundary = "****+++++******+++++++********"; URL apiUrl = new URL(url); final HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection(); conn.setConnectTimeout(10000); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); conn.connect(); OutputStream out = conn.getOutputStream(); PrintStream ps = new PrintStream(out); int index = 0; byte[] block = new byte[1024]; for (NameValuePair nameValuePair : data) { ps.print(twoHyphens + boundary + end); ps.print("Content-Disposition: form-data; name=\"" + nameValuePair.getName() + "\"" + end + end); final InputStream value = nameValuePair.getValue(); while (true) { final int rd = value.read(block, 0, block.length); if (rd < 1) { break; } ps.write(block, 0, rd); } value.close(); ps.print(end); } ps.print(twoHyphens + boundary + twoHyphens + end); ps.close(); boolean b = conn.getResponseCode() == 200; if (!b) { return new RESTResponse("HTTP " + conn.getResponseCode() + ": " + conn.getResponseMessage(), false, null); } else { InputStream inputStream = conn.getInputStream(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] arr = new byte[1024]; while (true) { int rd = inputStream.read(arr); if (rd < 1) break; baos.write(arr, 0, rd); } if (conn.getHeaderField("X-GZIPCompress") != null) { return new RESTResponse(null, false, baos.toString(0)); } else { return new RESTResponse(null, false, baos.toString()); } } finally { inputStream.close(); } } } catch (IOException e) { return new RESTResponse(e.toString(), false, null); } }
From source file:com.urhola.vehicletracker.connection.mattersoft.MatterSoftLiveHelsinki.java
private HttpURLConnection getOpenedConnection(List<NameValuePair> params, String responseMethod) throws ConnectionException { HttpURLConnection urlConnection; try {/*from w w w . j av a 2 s . c o m*/ URIBuilder b = new URIBuilder(BASE_URL); b.addParameters(params); URL url = b.build().toURL(); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setRequestMethod(responseMethod); urlConnection.setReadTimeout(TIME_OUT_LENGTH); urlConnection.setConnectTimeout(TIME_OUT_LENGTH); urlConnection.connect(); int responseCode = urlConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) throw new ConnectionException(urlConnection.getResponseMessage()); return urlConnection; } catch (URISyntaxException | IOException ex) { throw new ConnectionException(ex); } }
From source file:com.vizury.PushNotification.Engine.Sender.java
/** * Makes an HTTP POST request to a given endpoint. * <p/>//from w ww. j a v a2s . c om * <p/> * <strong>Note: </strong> the returned connected should not be disconnected, * otherwise it would kill persistent connections made using Keep-Alive. * * @param url endpoint to post the request. * @param contentType type of request. * @param body body of the request. * @return the underlying connection. * @throws java.io.IOException propagated from underlying methods. */ protected HttpURLConnection post(String url, String contentType, String body) throws IOException { if (url == null || body == null) { throw new IllegalArgumentException("arguments cannot be null"); } if (!url.startsWith("https://")) { logger.warn("URL does not use https: " + url); } logger.debug("Sending POST to " + url); logger.debug("POST body: " + body); byte[] bytes = body.getBytes(); HttpURLConnection conn = getConnection(url); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Authorization", "key=" + key); OutputStream out = conn.getOutputStream(); try { out.write(bytes); } finally { close(out); } return conn; }
From source file:org.belio.service.gateway.Gateway.java
private synchronized void doPostJson(JSONObject obj) { try {/* w ww. j a v a2 s . co m*/ // String urlParameters = "param1=a¶m2=b¶m3=c"; String request = "http://api.infobip.com/api/v3/sendsms/json"; URL url = new URL(request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("charset", "utf-8"); // connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setUseCaches(false); OutputStream wr = connection.getOutputStream(); // wr.writeBytes(urlParameters); wr.write(obj.toString().getBytes()); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } wr.close(); rd.close(); //s wr.close(); connection.disconnect(); } catch (MalformedURLException ex) { Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex); } catch (ProtocolException ex) { Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.pinterest.deployservice.events.EventSenderImpl.java
public void sendDeployEvent(String what, String tags, String data) throws Exception { JsonObject object = new JsonObject(); object.addProperty("what", what); object.addProperty("tags", tags); object.addProperty("data", data); final String paramsToSend = object.toString(); DataOutputStream output = null; HttpURLConnection connection = null; int retry = 0; while (retry < TOTAL_RETRY) { try {/* ww w . j av a 2s. c o m*/ URL requestUrl = new URL(this.URL); connection = (HttpURLConnection) requestUrl.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json; charset=utf8"); connection.setRequestProperty("Content-Length", Integer.toString(paramsToSend.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setRequestMethod("POST"); output = new DataOutputStream(connection.getOutputStream()); output.writeBytes(paramsToSend); output.flush(); output.close(); String result = IOUtils.toString(connection.getInputStream(), "UTF-8").toLowerCase(); LOG.info("Successfully send events to the statsboard: " + result); return; } catch (Exception e) { LOG.error("Failed to send event", e); } finally { IOUtils.closeQuietly(output); if (connection != null) { connection.disconnect(); } retry++; } } throw new DeployInternalException("Failed to send event"); }
From source file:com.pinterest.deployservice.chat.HipChatManager.java
@Override public void send(String from, String room, String message, String color) throws Exception { HashMap<String, String> params = new HashMap<>(); params.put(ROOM_ID_KEY, URLEncoder.encode(room, "UTF-8")); params.put(USER_KEY, URLEncoder.encode(from, "UTF-8")); params.put(MESSAGE_KEY, URLEncoder.encode(message, "UTF-8")); if (color != null) { params.put(COLOR_KEY, color);/* w w w .j a v a2s . c o m*/ } final String paramsToSend = this.constructQuery(params); String url = requestURL; DataOutputStream output = null; HttpURLConnection connection = null; for (int i = 0; i < TOTAL_RETRY; i++) { try { URL requestUrl = new URL(url); connection = (HttpURLConnection) requestUrl.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(paramsToSend.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); output = new DataOutputStream(connection.getOutputStream()); output.writeBytes(paramsToSend); return; } catch (Exception e) { LOG.error("Failed to send Hipchat message to room " + room, e); } finally { IOUtils.closeQuietly(output); if (connection != null) { connection.disconnect(); } } Thread.sleep(1000); } LOG.error("Failed to send Hipchat message to room " + room); }
From source file:com.sun.socialsite.web.rest.servlets.ProxyServlet.java
/** * Handles the HTTP <code>POST</code> method. * @param req servlet request//from w ww . j av a2 s. co m * @param resp servlet response */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { URL url = getURL(req, req.getParameter("uri")); HttpURLConnection con = (HttpURLConnection) (url.openConnection()); con.setDoOutput(true); con.setAllowUserInteraction(false); con.setUseCaches(false); // TODO: figure out why this is necessary for HTTPS URLs if (con instanceof HttpsURLConnection) { HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) { return true; } else { log.error("URL Host: " + urlHostName + " vs. " + session.getPeerHost()); return false; } } }; ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv); } // pass along all appropriate HTTP headers Enumeration headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()) { String hname = (String) headerNames.nextElement(); if (!unproxiedHeaders.contains(hname.toLowerCase())) { con.addRequestProperty(hname, req.getHeader(hname)); } } con.connect(); // read POST data from incoming request, write to outgoing request BufferedInputStream in = new BufferedInputStream(req.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(con.getOutputStream()); byte buffer[] = new byte[8192]; for (int count = 0; count != -1;) { count = in.read(buffer, 0, 8192); if (count != -1) out.write(buffer, 0, count); } in.close(); out.close(); out.flush(); // read result headers of POST, write to response Map<String, List<String>> headers = con.getHeaderFields(); for (String key : headers.keySet()) { if (key != null) { // TODO: why is this check necessary! List<String> header = headers.get(key); if (header.size() > 0) resp.setHeader(key, header.get(0)); } } // read result data of POST, write out to response in = new BufferedInputStream(con.getInputStream()); out = new BufferedOutputStream(resp.getOutputStream()); for (int count = 0; count != -1;) { count = in.read(buffer, 0, 8192); if (count != -1) out.write(buffer, 0, count); } in.close(); out.close(); out.flush(); con.disconnect(); }
From source file:de.thingweb.repository.RepositoryClient.java
/** This method takes a properties which you are looking for or a SPARQL query * @param search properties or a SPARQL query * @return JSON array of relevant TD files (=empty array means no match) * *//*from w w w .jav a2 s . c om*/ public JSONArray tdSearch(String search) throws Exception { URL myURL = new URL("http://" + repository_uri + ":" + repository_port + "/td?query=" + search); HttpURLConnection myURLConnection = (HttpURLConnection) myURL.openConnection(); myURLConnection.setRequestMethod("GET"); myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); myURLConnection.setDoInput(true); myURLConnection.setDoOutput(true); InputStream in = myURLConnection.getInputStream(); JSONArray jsonLDs = new JSONArray(streamToString(in)); System.out.println(streamToString(in)); return jsonLDs; }
From source file:net.bashtech.geobot.BotManager.java
public static String postDataLinkShortener(String postData) { URL url;/*from www . j a v a 2 s. c o m*/ HttpURLConnection conn; postData = "{\"longUrl\": \"" + postData + "\"}"; try { url = new URL("https://www.googleapis.com/urlshortener/v1/url"); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "CoeBot"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length)); PrintWriter out = new PrintWriter(conn.getOutputStream()); System.out.println(postData); out.print(postData); out.close(); String response = ""; Scanner inStream = new Scanner(conn.getInputStream()); while (inStream.hasNextLine()) response += (inStream.nextLine()); inStream.close(); return response; } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } return ""; }
From source file:com.example.pabrto.AppEngineClient.java
public static Response getOrPost(Request request) { mErrorMessage = null;//from w w w . ja v a2 s . c o m HttpURLConnection conn = null; Response response = null; try { conn = (HttpURLConnection) request.uri.openConnection(); // if (!mAuthenticator.authenticate(conn)) { // mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage(); // } else { if (request.headers != null) { for (String header : request.headers.keySet()) { for (String value : request.headers.get(header)) { conn.addRequestProperty(header, value); } } } if (request instanceof POST) { byte[] payload = ((POST) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); // ... OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); // conn.setFixedLengthStreamingMode(payload.length); // conn.getOutputStream().write(payload); int status = conn.getResponseCode(); if (status / 100 != 2) response = new Response(status, new Hashtable<String, List<String>>(), conn.getResponseMessage().getBytes()); } if (response == null) { int a = conn.getResponseCode(); InputStream a1 = conn.getErrorStream(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); byte[] body = readStream(in); response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body); // List<String> a = conn.getHeaderFields().get("aa"); } } } catch (IOException e) { e.printStackTrace(System.err); mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": " + e.getLocalizedMessage(); } finally { if (conn != null) conn.disconnect(); } return response; }