List of usage examples for java.net URLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:edu.csh.coursebrowser.SchoolActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_course_browser); ListView lv = (ListView) this.findViewById(R.id.schools); this.setTitle("Course Browser"); map_items = new HashMap<String, School>(); map = new ArrayList<String>(); this.sp = getPreferences(MODE_WORLD_READABLE); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, map); this.setTitle("Course Browser"); if (!sp.contains("firstRun")) { SharedPreferences.Editor e = sp.edit(); e.putBoolean("firstRun", false); e.commit();//from w ww. j a va 2 s . com Intent intent = new Intent(SchoolActivity.this, AboutActivity.class); startActivity(intent); } addItem(new School("01", "Saunder's College of Business")); addItem(new School("03", "College of Engineering")); addItem(new School("05", "College of Liberal Arts")); addItem(new School("06", "Applied Science & Technology")); addItem(new School("08", "NTID")); addItem(new School("10", "College of Science")); addItem(new School("11", "Wellness")); addItem(new School("17", "Academic Services")); addItem(new School("20", "Imaging Arts and Sciences")); addItem(new School("30", "Interdisciplinary Studies")); addItem(new School("40", "GCCIS")); addItem(new School("50", "Institute for Sustainability")); 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 School school = map_items.get(s); new AsyncTask<String, String, String>() { ProgressDialog p; protected void onPreExecute() { p = new ProgressDialog(SchoolActivity.this); p.setTitle("Fetching Info"); p.setMessage("Contacting Server..."); p.setCancelable(false); p.show(); } protected String doInBackground(String... school) { String params = "action=getDepartments&school=" + school[0] + "&quarter=20123"; 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(); return null; } return back; } protected void onPostExecute(String s) { if (s == null || s == "") { new AlertError(SchoolActivity.this, "IO Error!").show(); return; } try { JSONObject jso = new JSONObject(s); JSONArray jsa = new JSONArray(jso.getString("departments")); ArrayList<Department> depts = new ArrayList<Department>(); for (int i = 0; i < jsa.length(); ++i) { JSONObject obj = new JSONObject(jsa.get(i).toString()); depts.add(new Department(obj.getString("title"), obj.getString("id"), obj.getString("code"))); } } catch (JSONException e) { e.printStackTrace(); new AlertError(SchoolActivity.this, "Invalid JSON From Server").show(); p.dismiss(); return; } Intent intent = new Intent(SchoolActivity.this, DepartmentActivity.class); intent.putExtra("from", school.deptName); intent.putExtra("args", s); intent.putExtra("qCode", sp.getString("quarter", "20122")); startActivity(intent); p.dismiss(); } }.execute(school.deptNum); } }); }
From source file:org.exoplatform.wcm.connector.fckeditor.GadgetConnector.java
/** * Creates the file element.//from w ww.j av a 2 s . co m * * @param document The document. * @param applicationCategory The application category. * * @return the element * * @throws Exception the exception */ private Element createFileElement(Document document, ApplicationCategory applicationCategory, String host) throws Exception { Element files = document.createElement("Files"); List<Application> listApplication = applicationRegistryService.getApplications(applicationCategory, ApplicationType.GADGET); for (Application application : listApplication) { Gadget gadget = gadgetRegistryService.getGadget(application.getApplicationName()); Element file = document.createElement("File"); file.setAttribute("name", gadget.getName()); file.setAttribute("fileType", "nt_unstructured"); file.setAttribute("size", "0"); file.setAttribute("thumbnail", gadget.getThumbnail()); file.setAttribute("description", gadget.getDescription()); String fullurl = ""; if (gadget.isLocal()) { fullurl = "/" + PortalContainer.getCurrentRestContextName() + "/" + gadget.getUrl(); } else { fullurl = gadget.getUrl(); } file.setAttribute("url", fullurl); String data = "{\"context\":{\"country\":\"US\",\"language\":\"en\"},\"gadgets\":[{\"moduleId\":0,\"url\":\"" + fullurl + "\",\"prefs\":[]}]}"; URL url = new URL(host + "/eXoGadgetServer/gadgets/metadata"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); String strMetadata = IOUtils.toString(conn.getInputStream(), "UTF-8"); wr.close(); JSONObject metadata = new JSONObject(strMetadata.toString()); ConversationState conversationState = ConversationState.getCurrent(); String userId = conversationState.getIdentity().getUserId(); String token = createToken(gadget.getUrl(), userId, userId, new Random().nextLong(), "default"); JSONObject obj = metadata.getJSONArray("gadgets").getJSONObject(0); obj.put("secureToken", token); file.setAttribute("metadata", metadata.toString()); files.appendChild(file); } return files; }
From source file:ca.etsmtl.applets.etsmobile.api.SignetBackgroundThread.java
@SuppressWarnings("unchecked") public T fetchArray() { ArrayList<E> array = new ArrayList<E>(); try {//from ww w .j a v a 2 s . c o m final StringBuilder sb = new StringBuilder(); sb.append(urlStr); sb.append("/"); sb.append(action); final Gson gson = new Gson(); final String bodyParamsString = gson.toJson(bodyParams); final URL url = new URL(sb.toString()); final URLConnection conn = url.openConnection(); conn.addRequestProperty("Content-Type", "application/json"); conn.addRequestProperty("charset", "utf-8"); conn.setDoOutput(true); final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(bodyParamsString); wr.flush(); final StringWriter writer = new StringWriter(); final InputStream in = conn.getInputStream(); IOUtils.copy(in, writer); in.close(); wr.close(); final String jsonString = writer.toString(); final ArrayList<E> objectList = new ArrayList<E>(); JSONObject jsonObject; jsonObject = new JSONObject(jsonString); JSONArray jsonRootArray; jsonRootArray = jsonObject.getJSONObject("d").getJSONArray(liste); android.util.Log.d("JSON", jsonRootArray.toString()); for (int i = 0; i < jsonRootArray.length(); i++) { objectList.add(gson.fromJson(jsonRootArray.getJSONObject(i).toString(), typeOfClass)); } array = objectList; } catch (final IOException e) { e.printStackTrace(); } catch (final JSONException e) { e.printStackTrace(); } return (T) array; }
From source file:org.wso2.esb.integration.common.utils.clients.JSONClient.java
private JSONObject sendRequest(String addUrl, String query) throws IOException, JSONException { String charset = "UTF-8"; URLConnection connection = new URL(addUrl).openConnection(); connection.setDoOutput(true);/*w ww .j a va2 s . com*/ connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/json;charset=" + charset); OutputStream output = null; try { output = connection.getOutputStream(); output.write(query.getBytes(charset)); } finally { if (output != null) { try { output.close(); } catch (IOException logOrIgnore) { log.error("Error while closing the connection"); } } } InputStream response = connection.getInputStream(); String out = "[Fault] No Response."; if (response != null) { StringBuilder sb = new StringBuilder(); byte[] bytes = new byte[1024]; int len; while ((len = response.read(bytes)) != -1) { sb.append(new String(bytes, 0, len)); } out = sb.toString(); } JSONObject jsonObject = new JSONObject(out); return jsonObject; }
From source file:ubic.gemma.loader.protein.biomart.BiomartEnsemblNcbiFetcher.java
/** * Submit a xml query to biomart service return the returned data as a bufferedreader * //w ww. j a v a 2 s .c o m * @param urlToRead Biomart configured URL * @param data The query data for biomart * @return BufferedReader Stream to read data from */ private BufferedReader readFile(URL urlToRead, String data) { URLConnection conn = null; OutputStreamWriter writer = null; try { conn = urlToRead.openConnection(); conn.setDoOutput(true); writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); writer.close(); return new BufferedReader(new InputStreamReader(conn.getInputStream())); } catch (IOException e) { log.error(e); throw new RuntimeException(e); } }
From source file:com.qiqi8226.http.MainActivity.java
private void onBtnPost() { new AsyncTask<String, String, Void>() { @Override/*from www . jav a 2 s . c om*/ protected Void doInBackground(String... params) { URL url; try { url = new URL(params[0]); URLConnection conn = url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); bw.write(""); bw.flush(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = br.readLine()) != null) { publishProgress(line); } br.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onProgressUpdate(String... values) { tv.append(values[0] + "\n"); } }.execute("http://www.baidu.com/"); }
From source file:xtuaok.sharegyazo.HttpMultipartPostRequest.java
public String send() { URLConnection conn = null; String res = null;/*from ww w.j a va 2s . c o m*/ try { conn = new URL(mCgi).openConnection(); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); ((HttpURLConnection) conn).setRequestMethod("POST"); conn.setDoOutput(true); conn.connect(); OutputStream os = conn.getOutputStream(); os.write(createBoundaryMessage("imagedata").getBytes()); os.write(mByteData); String endBoundary = "\r\n--" + BOUNDARY + "--\r\n"; os.write(endBoundary.getBytes()); os.close(); InputStream is = conn.getInputStream(); res = convertToString(is); } catch (Exception e) { Log.d(LOG_TAG, e.getMessage() + ""); } finally { if (conn != null) { ((HttpURLConnection) conn).disconnect(); } } return res; }
From source file:org.apache.axis2.transport.testkit.http.JavaNetClient.java
public void sendMessage(ClientOptions options, ContentType contentType, byte[] message) throws Exception { URL url = new URL(channel.getEndpointReference().getAddress()); log.debug("Opening connection to " + url + " using " + URLConnection.class.getName()); try {//from w ww . j ava 2 s.c o m URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", contentType.toString()); if (contentType.getBaseType().equals("text/xml")) { connection.setRequestProperty("SOAPAction", ""); } OutputStream out = connection.getOutputStream(); out.write(message); out.close(); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; log.debug("Response code: " + httpConnection.getResponseCode()); log.debug("Response message: " + httpConnection.getResponseMessage()); int i = 0; String headerValue; while ((headerValue = httpConnection.getHeaderField(i)) != null) { String headerName = httpConnection.getHeaderFieldKey(i); if (headerName != null) { log.debug(headerName + ": " + headerValue); } else { log.debug(headerValue); } i++; } } InputStream in = connection.getInputStream(); IOUtils.copy(in, System.out); in.close(); } catch (IOException ex) { log.debug("Got exception", ex); throw ex; } }
From source file:eu.europa.esig.dss.DSSUtils.java
public static void writeToURLConnection(final URLConnection urlConnection, final byte[] bytes) throws DSSException { try {//from w w w .j a v a2s . c om final OutputStream out = urlConnection.getOutputStream(); out.write(bytes); out.close(); } catch (IOException e) { throw new DSSException(e); } }
From source file:com.seleritycorp.common.base.coreservices.RawCoreServiceClient.java
private String getRawResponse(String rawRequest, int timeoutMillis) throws IOException { URLConnection connection = apiUrl.openConnection(); connection.setRequestProperty("Accept", "text/plain"); connection.setRequestProperty("Content-type", "application/json"); connection.setRequestProperty("User-Agent", client); connection.setDoOutput(true);/*from ww w . j av a2 s . c o m*/ connection.setReadTimeout(timeoutMillis); final OutputStream out = connection.getOutputStream(); out.write(rawRequest.getBytes(StandardCharsets.UTF_8)); out.flush(); out.close(); log.debug("wrote request " + rawRequest + " (timeout wanted: " + timeoutMillis + ", actual: " + connection.getReadTimeout() + ")"); String response = null; try (final InputStream in = connection.getInputStream()) { response = IOUtils.toString(in, StandardCharsets.UTF_8); } return response; }