List of usage examples for java.io OutputStreamWriter write
public void write(int c) throws IOException
From source file:com.trafficspaces.api.controller.Connector.java
public String sendRequest(String path, String contentType, String method, String data) throws IOException, TrafficspacesAPIException { URL url = new URL(endPoint.baseURI + path); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true);/*from w ww . ja va2 s .co m*/ httpCon.setRequestMethod(method.toUpperCase()); String basicAuth = "Basic " + Base64.encodeBytes((endPoint.username + ":" + endPoint.password).getBytes()); httpCon.setRequestProperty("Authorization", basicAuth); httpCon.setRequestProperty("Content-Type", contentType + "; charset=UTF-8"); httpCon.setRequestProperty("Accept", contentType); if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) { httpCon.setRequestProperty("Content-Length", String.valueOf(data.length())); OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream()); out.write(data); out.close(); } else { httpCon.connect(); } char[] responseData = null; try { responseData = readResponseData(httpCon.getInputStream(), "UTF-8"); } catch (FileNotFoundException fnfe) { // HTTP 404. Ignore and return null } String responseDataString = null; if (responseData != null) { int responseCode = httpCon.getResponseCode(); String redirectURL = null; if ((responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_CREATED) && (redirectURL = httpCon.getHeaderField("Location")) != null) { //System.out.println("Response code = " +responseCode + ". Redirecting to " + redirectURL); return sendRequest(redirectURL, contentType); } if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_CREATED) { throw new TrafficspacesAPIException( "HTTP Error: " + responseCode + "; Data: " + new String(responseData)); } //System.out.println("Headers: " + httpCon.getHeaderFields()); //System.out.println("Data: " + new String(responseData)); responseDataString = new String(responseData); } return responseDataString; }
From source file:com.culvereq.vimp.networking.ConnectionHandler.java
public ServiceRecord addServiceRecord(TempServiceRecord serviceRecord) throws IOException, JSONException { URL requestURL = new URL(serviceURL + "add"); HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection(); connection.setDoInput(true);// w ww. j a v a2 s . com connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); String urlParameters = ""; urlParameters += "key=" + Globals.access_key; urlParameters += "&vehicle-id=" + serviceRecord.getParentVehicle().getId(); urlParameters += "&type-id=" + serviceRecord.getType().getValue(); urlParameters += "&service-desc=" + serviceRecord.getDescription(); urlParameters += "&service-date=" + serviceRecord.getServiceDate().getMillis() / 1000L; urlParameters += "&service-mileage=" + serviceRecord.getMileage(); connection.setRequestProperty("Content-Length", "" + urlParameters.getBytes().length); connection.setUseCaches(false); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(urlParameters); writer.flush(); writer.close(); int responseCode = connection.getResponseCode(); if (responseCode == 201) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONObject json = new JSONObject(response.toString()); return new Deserializer().deserializeService(json, response.toString()); } else if (responseCode == 400) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); throw new IOException(response.toString()); } else { throw new IOException("Got response code: " + responseCode); } }
From source file:de.micromata.genome.gwiki.plugin.rogmp3_1_0.CsvTable.java
public void store(File file) { StringBuilder sb = new StringBuilder(); for (String[] line : table) { sb.append(StringUtils.join(line, '|')).append("\n"); }//from w w w .j av a 2 s. c o m try { FileOutputStream fout = new FileOutputStream(file); OutputStreamWriter sout = new OutputStreamWriter(fout, encoding); sout.write(sb.toString()); IOUtils.closeQuietly(sout); IOUtils.closeQuietly(fout); } catch (IOException ex) { throw new RuntimeException("CsvTable; File write : " + file.getAbsolutePath() + "; " + ex.getMessage(), ex); } }
From source file:com.culvereq.vimp.networking.ConnectionHandler.java
public Vehicle addVehicle(TempVehicle vehicle) throws IOException, JSONException { URL requestURL = new URL(vehicleURL + "add"); HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection(); connection.setDoInput(true);/*from w w w . ja v a 2s.c o m*/ connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); String urlParameters = ""; urlParameters += "key=" + Globals.access_key; urlParameters += "&vehicle-name=" + vehicle.getName(); urlParameters += "&vehicle-type-id=" + vehicle.getType().getValue(); urlParameters += "&vehicle-make=" + vehicle.getMake(); urlParameters += "&vehicle-model" + vehicle.getModel(); urlParameters += "&vehicle-year" + vehicle.getYear(); urlParameters += "&vehicle-mileage" + vehicle.getMileage(); urlParameters += "&vehicle-vin" + vehicle.getVin(); urlParameters += "&vehicle-license-no" + vehicle.getLicenseNumber(); connection.setRequestProperty("Content-Length", "" + urlParameters.getBytes().length); connection.setUseCaches(false); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(urlParameters); writer.flush(); writer.close(); int responseCode = connection.getResponseCode(); if (responseCode == 201) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONObject json = new JSONObject(response.toString()); return new Deserializer().deserializeVehicle(json, response.toString()); } else if (responseCode == 400) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); throw new IOException(response.toString()); } else { throw new IOException("Got response code: " + responseCode); } }
From source file:com.support.android.designlibdemo.DetailContactActivity.java
public String postData(String sURL, String sData) { try {/*www . j a v a2s . c om*/ String data = URLEncoder.encode("jsonString", "UTF-8") + "=" + URLEncoder.encode(sData, "UTF-8"); URL url = new URL(sURL); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } return sb.toString(); } catch (Exception e) { e.printStackTrace(); } return ""; }
From source file:com.tomcat.monitor.zabbix.ZabbixSender.java
public void send(final String zabbixServer, final int zabbixPort, int zabbixTimeout, final String host, final String key, final String value) throws IOException { final byte[] response = new byte[1024]; final long start = System.currentTimeMillis(); final int TIMEOUT = zabbixTimeout * 1000; final StringBuilder message = new StringBuilder("<req><host>"); message.append(new String(Base64.encodeBase64(host.getBytes()))); message.append("</host><key>"); message.append(new String(Base64.encodeBase64(key.getBytes()))); message.append("</key><data>"); message.append(new String(Base64.encodeBase64(value.getBytes()))); message.append("</data></req>"); if (log.isDebugEnabled()) { log.debug("sending " + message); }//from w w w . j a va 2 s. co m Socket zabbix = null; OutputStreamWriter out = null; InputStream in = null; try { zabbix = new Socket(zabbixServer, zabbixPort); zabbix.setSoTimeout(TIMEOUT); out = new OutputStreamWriter(zabbix.getOutputStream()); out.write(message.toString()); out.flush(); in = zabbix.getInputStream(); final int read = in.read(response); if (log.isDebugEnabled()) { log.debug("received " + new String(response)); } if (read != 2 || response[0] != 'O' || response[1] != 'K') { log.warn("received unexpected response '" + new String(response) + "' for key '" + key + "'"); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } if (zabbix != null) { zabbix.close(); } } log.info("send() " + (System.currentTimeMillis() - start) + " ms"); }
From source file:github.nisrulz.optimushttp.HttpReq.java
@Override protected String doInBackground(HttpReqPkg... params) { URL url;//from www . ja v a 2 s.c o 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:at.florian_lentsch.expirysync.net.JsonCaller.java
private void writeParams(HttpURLConnection connection, JSONObject params) throws IOException, JSONException, UnsupportedEncodingException { OutputStream os = connection.getOutputStream(); final OutputStreamWriter osw = new OutputStreamWriter(os); final String toWriteOut = params.toString(); osw.write(toWriteOut); osw.close();//from ww w . j ava 2 s .com }
From source file:game.Clue.JerseyClient.java
public void sendPUT(String name) { System.out.println("SendPUT method called"); try {// w w w .j a va 2 s .c om JSONObject jsonObject = new JSONObject("{name:" + name + "}"); URL url = new URL( "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/game/player1"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); //setDoOutput(true); connection.setRequestProperty("PUT", "application/json"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(jsonObject.toString()); System.out.println("Sent PUT message to server"); out.close(); } catch (Exception e) { e.printStackTrace(); } }
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 {/*from w w w . j av a2 s.c o m*/ 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(); } }