List of usage examples for java.io OutputStreamWriter flush
public void flush() throws IOException
From source file:de.hybris.platform.marketplaceintegrationbackoffice.utils.MarketplaceintegrationbackofficeHttpUtilImpl.java
/** * Post data//from w ww . ja va 2 s . c o m * * @param url * @param data * @return boolean * @throws IOException */ @Override public boolean post(final String url, final String data) throws IOException { httpURL = new URL(url); final HttpURLConnection conn = (HttpURLConnection) httpURL.openConnection(); conn.setDoOutput(true); initConnection(conn); OutputStreamWriter writer = null; OutputStream outStream = null; try { outStream = conn.getOutputStream(); writer = new OutputStreamWriter(outStream, "UTF-8"); writer.write(data); writer.flush(); } finally { if (outStream != null) { try { outStream.close(); } catch (final IOException ex) { LOG.error(ex.getMessage(), ex); } } if (writer != null) { try { writer.close(); } catch (final IOException ex) { LOG.error(ex.getMessage(), ex); } } } final int status = conn.getResponseCode(); conn.disconnect(); return status == HttpURLConnection.HTTP_OK; }
From source file:com.commerce4j.storefront.controllers.CatalogController.java
/** * @param request//from ww w .j a v a2 s .c om * @param response */ public void featuredBrands(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> responseModel = new HashMap<String, Object>(); response.setContentType(HTTP_HEADER_JSON); Gson gson = new GsonBuilder().create(); BrandDAO brandDAO = (BrandDAO) getApplicationContext().getBean("brandDAO"); List<BrandDTO> brands = brandDAO.findAllFeatured(); responseModel.put("responseCode", SUCCESS); responseModel.put("responseMessage", "Login Completo"); responseModel.put("brands", brands); // serialize output try { OutputStreamWriter os = new OutputStreamWriter(response.getOutputStream(), "UTF8"); String data = gson.toJson(responseModel); os.write(data); os.flush(); os.close(); } catch (IOException e) { logger.fatal(e); } }
From source file:org.teiid.arquillian.IntegrationTestRestWebserviceGeneration.java
private String httpCall(String url, String method, String params) throws Exception { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod(method); connection.setDoOutput(true);/*from ww w . j av a 2s. com*/ if (method.equalsIgnoreCase("post")) { OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream()); wr.write(params); wr.flush(); } int code = connection.getResponseCode(); if (code >= 400) { throw new TeiidRuntimeException(String.valueOf(code)); } return ObjectConverterUtil .convertToString(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8"))); }
From source file:org.apache.hadoop.chukwa.datatrigger.HttpTriggerAction.java
private void makeHttpRequest(URL url, String method, Map<String, String> headers, String body, int connectTimeout, int readTimeout) throws IOException { if (url == null) { return;/*from ww w. j a v a 2 s. c o m*/ } // initialize the connection HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(method); conn.setDoInput(true); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); // set headers boolean contentLengthExists = false; if (headers != null) { for (Entry<String, String> entry : headers.entrySet()) { String name = entry.getKey(); String value = entry.getValue(); if (log.isDebugEnabled()) { log.debug("Setting header " + name + ": " + value); } if (name.equalsIgnoreCase("content-length")) { contentLengthExists = true; } conn.setRequestProperty(name, value); } } // set content-length if not already set if (!"GET".equals(method) && !contentLengthExists) { String contentLength = body != null ? String.valueOf(body.length()) : "0"; conn.setRequestProperty("Content-Length", contentLength); } // send body if it exists if (body != null) { conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), Charset.forName("UTF-8")); writer.write(body); writer.flush(); writer.close(); } else { conn.setDoOutput(false); } // read reponse code/message and dump response log.info("Making HTTP " + method + " to: " + url); int responseCode = conn.getResponseCode(); log.info("HTTP Response code: " + responseCode); if (responseCode != 200) { log.info("HTTP Response message: " + conn.getResponseMessage()); } else { BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8"))); String line; StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { if (sb.length() > 0) { sb.append("\n"); } sb.append(line); } log.info("HTTP Response:\n" + sb); reader.close(); } conn.disconnect(); }
From source file:africastalkinggateway.AfricasTalkingGateway.java
private String sendPOSTRequest(HashMap<String, String> dataMap_, String urlString_) throws Exception { try {/*from w ww. j ava 2 s . co m*/ String data = new String(); Iterator<Entry<String, String>> it = dataMap_.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next(); data += URLEncoder.encode(pairs.getKey().toString(), "UTF-8"); data += "=" + URLEncoder.encode(pairs.getValue().toString(), "UTF-8"); if (it.hasNext()) data += "&"; } URL url = new URL(urlString_); URLConnection conn = url.openConnection(); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("apikey", _apiKey); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); HttpURLConnection http_conn = (HttpURLConnection) conn; responseCode = http_conn.getResponseCode(); BufferedReader reader; if (responseCode == HTTP_CODE_OK || responseCode == HTTP_CODE_CREATED) reader = new BufferedReader(new InputStreamReader(http_conn.getInputStream())); else reader = new BufferedReader(new InputStreamReader(http_conn.getErrorStream())); String response = reader.readLine(); if (DEBUG) System.out.println(response); reader.close(); return response; } catch (Exception e) { throw e; } }
From source file:org.geoserver.wms.describelayer.GeoJSONDescribeLayerResponse.java
/** * Actually write the passed DescribeLayerModel on the OutputStream *//*from ww w . j av a 2 s . co m*/ public void write(DescribeLayerModel layers, DescribeLayerRequest request, OutputStream output) throws ServiceException, IOException { switch (type) { case JSON: OutputStreamWriter outWriter = null; try { outWriter = new OutputStreamWriter(output, wms.getGeoServer().getSettings().getCharset()); writeJSON(outWriter, layers); } finally { if (outWriter != null) { outWriter.flush(); IOUtils.closeQuietly(outWriter); } } case JSONP: writeJSONP(output, layers); } }
From source file:com.gdevelop.gwt.syncrpc.RemoteServiceSyncProxy.java
public Object doInvoke(RequestCallbackAdapter.ResponseReader responseReader, String requestData) throws Throwable { HttpURLConnection connection = null; InputStream is = null;/*from www. ja v a2s . c om*/ int statusCode; if (DUMP_PAYLOAD) { log.debug("Send request to {}", remoteServiceURL); log.debug("Request payload: {}", requestData); } // Send request CookieHandler oldCookieHandler = CookieHandler.getDefault(); try { CookieHandler.setDefault(cookieManager); URL url = new URL(remoteServiceURL); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty(RpcRequestBuilder.STRONG_NAME_HEADER, serializationPolicyName); connection.setRequestProperty(RpcRequestBuilder.MODULE_BASE_HEADER, moduleBaseURL); connection.setRequestProperty("Content-Type", "text/x-gwt-rpc; charset=utf-8"); connection.setRequestProperty("Content-Length", "" + requestData.getBytes("UTF-8").length); CookieStore store = cookieManager.getCookieStore(); String cookiesStr = ""; for (HttpCookie cookie : store.getCookies()) { if (!"".equals(cookiesStr)) cookiesStr += "; "; cookiesStr += cookie.getName() + "=" + cookie.getValue(); } connection.setRequestProperty("Cookie", cookiesStr); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(requestData); writer.flush(); writer.close(); } catch (IOException e) { throw new InvocationException("IOException while sending RPC request", e); } finally { CookieHandler.setDefault(oldCookieHandler); } // Receive and process response try { is = connection.getInputStream(); statusCode = connection.getResponseCode(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) > 0) { baos.write(buffer, 0, len); } String encodedResponse = baos.toString("UTF8"); if (DUMP_PAYLOAD) { log.debug("Response code: {}", statusCode); log.debug("Response payload: {}", encodedResponse); } // System.out.println("Response payload (len = " + encodedResponse.length() + "): " + encodedResponse); if (statusCode != HttpURLConnection.HTTP_OK) { throw new StatusCodeException(statusCode, encodedResponse); } else if (encodedResponse == null) { // This can happen if the XHR is interrupted by the server dying throw new InvocationException("No response payload"); } else if (isReturnValue(encodedResponse)) { encodedResponse = encodedResponse.substring(4); return responseReader.read(createStreamReader(encodedResponse)); } else if (isThrownException(encodedResponse)) { encodedResponse = encodedResponse.substring(4); Throwable throwable = (Throwable) createStreamReader(encodedResponse).readObject(); throw throwable; } else { throw new InvocationException("Unknown response " + encodedResponse); } } catch (IOException e) { log.error("error response: {}", IOUtils.toString(connection.getErrorStream())); throw new InvocationException("IOException while receiving RPC response", e); } catch (SerializationException e) { throw new InvocationException("Error while deserialization response", e); } finally { if (is != null) { try { is.close(); } catch (IOException ignore) { } } if (connection != null) { // connection.disconnect(); } } }
From source file:github.nisrulz.optimushttp.HttpReq.java
@Override protected String doInBackground(HttpReqPkg... params) { URL url;/* w ww .j a va 2 s . co m*/ BufferedReader reader = null; String username = params[0].getUsername(); String password = params[0].getPassword(); String authStringEnc = null; if (username != null && password != null) { String authString = username + ":" + password; byte[] authEncBytes; authEncBytes = Base64.encode(authString.getBytes(), Base64.DEFAULT); authStringEnc = new String(authEncBytes); } String uri = params[0].getUri(); if (params[0].getMethod().equals("GET")) { uri += "?" + params[0].getEncodedParams(); } try { StringBuilder sb; // create the HttpURLConnection url = new URL(uri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (authStringEnc != null) { connection.setRequestProperty("Authorization", "Basic " + authStringEnc); } if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT") || params[0].getMethod().equals("DELETE")) { // enable writing output to this url connection.setDoOutput(true); } if (params[0].getMethod().equals("POST")) { connection.setRequestMethod("POST"); } else if (params[0].getMethod().equals("GET")) { connection.setRequestMethod("GET"); } else if (params[0].getMethod().equals("PUT")) { connection.setRequestMethod("PUT"); } else if (params[0].getMethod().equals("DELETE")) { connection.setRequestMethod("DELETE"); } // give it x seconds to respond connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(readTimeout); connection.setRequestProperty("Content-Type", contentType); for (int i = 0; i < headerMap.size(); i++) { connection.setRequestProperty(headerMap.keyAt(i), headerMap.valueAt(i)); } connection.setRequestProperty("Content-Length", "" + params[0].getEncodedParams().getBytes().length); connection.connect(); if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT")) { OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(params[0].getEncodedParams()); writer.flush(); writer.close(); } // read the output from the server InputStream in; resCode = connection.getResponseCode(); resMsg = connection.getResponseMessage(); if (resCode != HttpURLConnection.HTTP_OK) { in = connection.getErrorStream(); } else { in = connection.getInputStream(); } reader = new BufferedReader(new InputStreamReader(in)); sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } sb.append(resCode).append(" : ").append(resMsg); return sb.toString(); } catch (Exception e) { listener.onFailure(Integer.toString(resCode) + " : " + resMsg); e.printStackTrace(); } finally { // close the reader; this can throw an exception too, so // wrap it in another try/catch block. if (reader != null) { try { reader.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } return null; }
From source file:edu.csh.coursebrowser.CourseActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_course); // Show the Up button in the action bar. this.getActionBar().setHomeButtonEnabled(false); map_item = new HashMap<String, Course>(); map = new ArrayList<String>(); Bundle args = this.getIntent().getExtras(); this.setTitle(args.getCharSequence("title")); try {/* w w w . j a v a 2s . com*/ JSONObject jso = new JSONObject(args.get("args").toString()); JSONArray jsa = new JSONArray(jso.getString("courses")); ListView lv = (ListView) this.findViewById(R.id.course_list); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, map); for (int i = 0; i < jsa.length(); ++i) { String s = jsa.getString(i); JSONObject obj = new JSONObject(s); Course course = new Course(obj.getString("title"), obj.getString("department"), obj.getString("course"), obj.getString("description"), obj.getString("id")); addItem(course); Log.v("Added", course.toString()); } lv.setAdapter(adapter); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { String s = ((TextView) arg1).getText().toString(); final Course course = map_item.get(s); new AsyncTask<String, String, String>() { ProgressDialog p; protected void onPreExecute() { p = new ProgressDialog(CourseActivity.this); p.setTitle("Fetching Info"); p.setMessage("Contacting Server..."); p.setCancelable(false); p.show(); } protected String doInBackground(String... dep) { String params = "action=getSections&course=" + course.id; Log.v("Params", params); URL url; String back = ""; try { url = new URL("http://iota.csh.rit" + ".edu/schedule/js/browseAjax" + ".php"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(params); writer.flush(); String line; BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream())); while ((line = reader.readLine()) != null) { Log.v("Back:", line); back += line; } writer.close(); reader.close(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); p.dismiss(); return null; } return back; } protected void onPostExecute(String s) { if (s == null || s == "") { new AlertError(CourseActivity.this, "IO Error!").show(); return; } try { JSONObject jso = new JSONObject(s); JSONArray jsa = new JSONArray(jso.getString("sections")); } catch (JSONException e) { e.printStackTrace(); new AlertError(CourseActivity.this, "Invalid JSON From Server").show(); p.dismiss(); return; } Intent intent = new Intent(CourseActivity.this, SectionsActivity.class); intent.putExtra("title", course.title); intent.putExtra("id", course.id); intent.putExtra("description", course.description); intent.putExtra("args", s); startActivity(intent); p.dismiss(); } }.execute(course.id); } }); } catch (JSONException e) { // TODO Auto-generated catch block new AlertError(this, "Invalid JSON"); e.printStackTrace(); } }
From source file:fr.irit.sparql.Proxy.SparqlProxy.java
public boolean storeDataString(StringBuilder query) throws SparqlQueryMalFormedException, SparqlEndpointUnreachableException { boolean ret = true; SparqlProxy.cleanString(query);// w w w .ja v a 2s. c om HttpURLConnection connection = null; try { String urlParameters = "update=" + URLEncoder.encode(query.toString(), "UTF-8"); URL url = new URL(this.urlServer + "update"); // Create connection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(urlParameters); writer.flush(); String line; BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String rep = ""; while ((line = reader.readLine()) != null) { rep += line; } writer.close(); reader.close(); } catch (UnsupportedEncodingException ex) { throw new SparqlQueryMalFormedException("Encoding unsupported"); } catch (MalformedURLException ex) { throw new SparqlQueryMalFormedException("Query malformed"); } catch (IOException ex) { throw new SparqlEndpointUnreachableException(ex); } finally { if (connection != null) { connection.disconnect(); } } return ret; }