List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:com.PAB.ibeaconreference.AppEngineSpatial.java
public static Response getOrPost(Request request) { mErrorMessage = null;// w w w .j a v a 2 s.co 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 PUT) { byte[] payload = ((PUT) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("PUT"); 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(); } 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(); if (a == 401) { response = new Response(a, conn.getHeaderFields(), new byte[] {}); } InputStream a1 = conn.getErrorStream(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); byte[] body = readStream(in); a12 = new String(body, "US-ASCII"); response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body); // List<String> a = conn.getHeaderFields().get("aa"); } } } catch (IOException e) { e.printStackTrace(System.err); } finally { if (conn != null) conn.disconnect(); } return response; }
From source file:de.jaetzold.philips.hue.HueBridgeComm.java
List<JSONObject> request(RM method, String fullPath, String json) throws IOException { final URL url = new URL(baseUrl, fullPath); log.fine("Request to " + method + " " + url + (json != null && json.length() > 0 ? ": " + json : "")); final URLConnection connection = url.openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setRequestMethod(method.name()); if (json != null && json.length() > 0) { if (method == RM.GET || method == RM.DELETE) { throw new HueCommException("Will not send json content for request method " + method); }// ww w . j a va 2 s . c o m httpConnection.setDoOutput(true); httpConnection.getOutputStream().write(json.getBytes(REQUEST_CHARSET)); } } else { throw new IllegalStateException("The current baseUrl \"" + baseUrl + "\" is not http?"); } final BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream(), REQUEST_CHARSET)); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line).append('\n'); } log.fine("Response from " + method + " " + url + ": " + builder); final String jsonString = builder.toString(); List<JSONObject> result = new ArrayList<>(); if (jsonString.trim().startsWith("{")) { result.add(new JSONObject(jsonString)); } else { final JSONArray array = new JSONArray(jsonString); for (int i = 0; i < array.length(); i++) { result.add(array.getJSONObject(i)); } } return result; }
From source file:eu.codeplumbers.cosi.api.tasks.RegisterDeviceTask.java
@Override protected Device doInBackground(Void... voids) { URL urlO = null;/* w ww .ja va 2 s.c o m*/ try { urlO = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); OutputStream os = conn.getOutputStream(); os.write(deviceString.getBytes("UTF-8")); os.flush(); // read the response int status = conn.getResponseCode(); InputStream in = null; if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { in = conn.getErrorStream(); } else { in = conn.getInputStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONObject jsonObject = new JSONObject(result); if (jsonObject != null) { if (jsonObject.has("login")) { resultDevice = new Device(); resultDevice.setUrl(url.replace("/device/", "")); //Log.d(getClass().getName(), "Token="+jsonObject.getString("login")); resultDevice.setLogin(jsonObject.getString("login")); resultDevice.setPassword(jsonObject.getString("password")); resultDevice.setPermissions(jsonObject.getString("permissions")); resultDevice.setFirstSyncDone(false); resultDevice.setSyncCalls(false); resultDevice.setSyncContacts(false); resultDevice.setSyncFiles(false); resultDevice.setSyncNotes(false); resultDevice.save(); } else { errorMessage = jsonObject.getString("error"); } } in.close(); conn.disconnect(); } catch (MalformedURLException e) { errorMessage = e.getLocalizedMessage(); } catch (ProtocolException e) { errorMessage = e.getLocalizedMessage(); } catch (IOException e) { errorMessage = e.getLocalizedMessage(); } catch (JSONException e) { errorMessage = e.getLocalizedMessage(); } return resultDevice; }
From source file:com.mabi87.httprequestbuilder.HTTPRequest.java
/** * @throws IOException/*www . j a va 2s .co m*/ * throws from HttpURLConnection method. * @return the HTTPResponse object */ private HTTPResponse post() throws IOException { URL url = new URL(mPath); HttpURLConnection lConnection = (HttpURLConnection) url.openConnection(); lConnection.setReadTimeout(mReadTimeoutMillis); lConnection.setConnectTimeout(mConnectTimeoutMillis); lConnection.setRequestMethod("POST"); lConnection.setDoInput(true); lConnection.setDoOutput(true); OutputStream lOutStream = lConnection.getOutputStream(); BufferedWriter lWriter = new BufferedWriter(new OutputStreamWriter(lOutStream, "UTF-8")); lWriter.write(getQuery(mParameters)); lWriter.flush(); lWriter.close(); lOutStream.close(); HTTPResponse response = readPage(lConnection); return response; }
From source file:export.GarminUploader.java
private void postData(HttpURLConnection conn, FormValues fv) throws IOException { OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); if (fv != null) { fv.write(wr);//w w w .j a v a 2 s.c o m } wr.flush(); wr.close(); }
From source file:com.youTransactor.uCube.mdm.task.DownloadBinaryTask.java
@Override protected void start() { HttpURLConnection urlConnection = null; try {/*from ww w . j a v a 2 s.c om*/ String url = GET_BINARY_WS + String.valueOf(binaryUpdate.getCfg().getType()) + '/' + deviceInfos.getPartNumber() + '/' + deviceInfos.getSerial(); urlConnection = MDMManager.getInstance().initRequest(url, MDMManager.POST_METHOD); urlConnection.setRequestProperty("Content-Type", "application/octet-stream"); urlConnection.getOutputStream().write(certificate); HTTPResponseCode = urlConnection.getResponseCode(); if (HTTPResponseCode == 200) { byte[] response = IOUtils.toByteArray(urlConnection.getInputStream()); if (parseResponse(response)) { notifyMonitor(TaskEvent.SUCCESS, binaryUpdate); } else { notifyMonitor(TaskEvent.FAILED); } } else { LogManager.debug(MDMManager.class.getSimpleName(), "config WS error: " + HTTPResponseCode); notifyMonitor(TaskEvent.FAILED); } } catch (Exception e) { LogManager.debug(MDMManager.class.getSimpleName(), "config WS error", e); notifyMonitor(TaskEvent.FAILED); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } }
From source file:mobi.espier.lgc.data.UploadHelper.java
private String doHttpPostAndGetResponse(String url, byte[] data) { if (TextUtils.isEmpty(url) || data == null || data.length < 1) { return null; }//from ww w. j a v a2 s . c om String response = null; try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); OutputStream outStream = conn.getOutputStream(); outStream.write(data); int mResponseCode = conn.getResponseCode(); if (mResponseCode == 200) { response = getHttpResponse(conn); } conn.disconnect(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (SocketTimeoutException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return response; }
From source file:com.trimble.tekla.teamcity.HttpConnector.java
public void PostPayload(TeamcityConfiguration conf, String url, String payload) { try {/*from w ww . j a v a 2 s . c o m*/ String urlstr = conf.getUrl() + url; URL urldata = new URL(urlstr); logger.warn("Hook Request: " + urlstr); String authStr = conf.getUserName() + ":" + conf.getPassWord(); String authEncoded = Base64.encodeBase64String(authStr.getBytes()); HttpURLConnection connection = (HttpURLConnection) urldata.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Authorization", "Basic " + authEncoded); if (payload != null) { connection.setRequestProperty("Content-Type", "application/xml; charset=utf-8"); connection.setRequestProperty("Content-Length", Integer.toString(payload.length())); connection.getOutputStream().write(payload.getBytes("UTF8")); } InputStream content = (InputStream) connection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(content)); StringBuilder dataout = new StringBuilder(); String line; while ((line = in.readLine()) != null) { dataout.append(line); } logger.warn("Hook Reply: " + line); } catch (Exception e) { logger.debug("Hook Exception: " + e.getMessage()); e.printStackTrace(); } }
From source file:com.geocent.owf.openlayers.DataRequestProxy.java
/** * Gets the data from the provided remote URL. * Note that the data will be returned from the method and not automatically * populated into the response object./*from w ww . j av a2 s.c o m*/ * * @param request ServletRequest object containing the request data. * @param response ServletResponse object for the response information. * @param url URL from which the data will be retrieved. * @return Data from the provided remote URL. * @throws IOException */ public String getData(HttpServletRequest request, HttpServletResponse response, String url) throws IOException { if (!allowUrl(url)) { throw new UnknownHostException("Request to invalid host not allowed."); } HttpURLConnection connection = (HttpURLConnection) (new URL(url).openConnection()); connection.setRequestMethod(request.getMethod()); // Detects a request with a payload inside the message body if (request.getContentLength() > 0) { connection.setRequestProperty("Content-Type", request.getContentType()); connection.setDoOutput(true); connection.setDoInput(true); byte[] requestPayload = IOUtils.toByteArray(request.getInputStream()); connection.getOutputStream().write(requestPayload); connection.getOutputStream().flush(); } // Create handler for the given content type and proxy the extracted information Handler contentHandler = HandlerFactory.getHandler(connection.getContentType()); return contentHandler.handleContent(response, connection.getInputStream()); }
From source file:logout2_servlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from ww w. j a v a2s . co m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String access_token = ""; Cookie cookie = null; Cookie[] cookies = request.getCookies(); for (int i = 0; i < cookies.length; i++) { Cookie cookie1 = cookies[i]; if (cookies[i].getName().equals("access_token")) { access_token = cookie1.getValue(); cookie = cookie1; } } System.out.println("TOKEN = " + access_token); String USER_AGENT = "Mozilla/5.0"; String url = "http://localhost:8082/Identity_Service/logout_servlet"; URL connection = new URL(url); HttpURLConnection con = (HttpURLConnection) connection.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "access_token=" + access_token; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder resp = new StringBuilder(); while ((inputLine = in.readLine()) != null) { resp.append(inputLine); } in.close(); JSONParser parser = new JSONParser(); JSONObject obj = null; try { obj = (JSONObject) parser.parse(resp.toString()); } catch (ParseException ex) { Logger.getLogger(logout2_servlet.class.getName()).log(Level.SEVERE, null, ex); } String status = (String) obj.get("status"); System.out.println(status); if (status.equals("ok")) { cookie.setMaxAge(0); response.sendRedirect("login.jsp"); } else { } }