List of usage examples for java.net URLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:com.qiqi8226.http.MainActivity.java
private void onBtnPost() { new AsyncTask<String, String, Void>() { @Override//from ww w . j a va2 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:com.util.httpAccount.java
public String setAccountObject(AccountLight account, String user) throws UnsupportedEncodingException, MalformedURLException, IOException { String respuesta = null;/*from ww w. j av a 2 s . c om*/ String myUrl = "http://192.168.5.44/app_dev.php/cus/setaccount/" + user + ".json"; URL url = new URL(myUrl); try { //abrimos la conexin URLConnection conn = url.openConnection(); //especificamos que vamos a escribir conn.setDoOutput(true); String data = URLEncoder.encode("firstName", "UTF-8") + "=" + URLEncoder.encode(account.getFirstName(), "UTF-8"); data += "&" + URLEncoder.encode("lastName", "UTF-8") + "=" + URLEncoder.encode(account.getLastName(), "UTF-8"); data += "&" + URLEncoder.encode("address", "UTF-8") + "=" + URLEncoder.encode(account.getAddress(), "UTF-8"); data += "&" + URLEncoder.encode("city", "UTF-8") + "=" + URLEncoder.encode(account.getCity(), "UTF-8"); data += "&" + URLEncoder.encode("postalCode", "UTF-8") + "=" + URLEncoder.encode(account.getPostalCode(), "UTF-8"); data += "&" + URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(account.getEmail(), "UTF-8"); data += "&" + URLEncoder.encode("languaje", "UTF-8") + "=" + URLEncoder.encode(String.valueOf(account.getLanguaje_id()), "UTF-8"); data += "&" + URLEncoder.encode("notifyEmail", "UTF-8") + "=" + URLEncoder.encode(String.valueOf(account.isNotifyEmail()), "UTF-8"); data += "&" + URLEncoder.encode("notifyFlag", "UTF-8") + "=" + URLEncoder.encode(String.valueOf(account.isNotityFlag()), "UTF-8"); //escribimos try ( //obtenemos el flujo de escritura OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream())) { //escribimos wr.write(data); wr.flush(); //cerramos la conexin } //obtenemos el flujo de lectura BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String linea; //procesamos al salida while ((linea = rd.readLine()) != null) { respuesta += linea; } } catch (Exception e) { e.printStackTrace(); respuesta = null; } System.out.println(respuesta); // TODO code application logic here return respuesta; }
From source file:com.support.android.designlibdemo.DetailContactActivity.java
public String postData(String sURL, String sData) { try {/*w w w. j a va2 s. c o m*/ 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:be.apsu.extremon.probes.tsp.TSPProbe.java
private TimeStampResponse probe(TimeStampRequest request) throws IOException, TSPException { URLConnection connection = this.url.openConnection(); connection.setDoInput(true);/*from ww w. j a v a2s. com*/ connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestProperty("Content-Type", "application/timestamp-query"); OutputStream outputStream = (connection.getOutputStream()); outputStream.write(request.getEncoded()); outputStream.flush(); outputStream.close(); InputStream inputStream = connection.getInputStream(); TimeStampResponse response = new TimeStampResponse(inputStream); inputStream.close(); return response; }
From source file:ca.etsmtl.applets.etsmobile.api.SignetBackgroundThread.java
@SuppressWarnings("unchecked") public T fetchObject() { T object = null;//from ww w. j av a2 s . c o m try { 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; 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(); JSONObject jsonObject; jsonObject = new JSONObject(jsonString); JSONObject jsonRootArray; jsonRootArray = jsonObject.getJSONObject("d"); object = (T) gson.fromJson(jsonRootArray.toString(), typeOfClass); android.util.Log.d("JSON", jsonRootArray.toString()); } catch (final MalformedURLException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } catch (final JSONException e) { e.printStackTrace(); } return object; }
From source file:org.spoutcraft.launcher.api.util.Download.java
@SuppressWarnings("unused") public void run() { ReadableByteChannel rbc = null; FileOutputStream fos = null;//from ww w .jav a2 s . co m try { URLConnection conn = url.openConnection(); conn.setDoInput(true); conn.setDoOutput(false); System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19"); HttpURLConnection.setFollowRedirects(true); conn.setUseCaches(false); ((HttpURLConnection) conn).setInstanceFollowRedirects(true); int response = ((HttpURLConnection) conn).getResponseCode(); InputStream in = getConnectionInputStream(conn); size = conn.getContentLength(); outFile = new File(outPath); outFile.delete(); rbc = Channels.newChannel(in); fos = new FileOutputStream(outFile); stateChanged(); Thread progress = new MonitorThread(Thread.currentThread(), rbc); progress.start(); fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE); in.close(); rbc.close(); progress.interrupt(); if (size > 0) { if (size == outFile.length()) { result = Result.SUCCESS; } } else { result = Result.SUCCESS; } } catch (PermissionDeniedException e) { result = Result.PERMISSION_DENIED; } catch (DownloadException e) { result = Result.FAILURE; } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(fos); IOUtils.closeQuietly(rbc); } }
From source file:com.linkedin.pinot.controller.helix.ControllerTest.java
public JSONObject getDebugInfo(final String uri) throws Exception { final URLConnection conn = new URL(BROKER_BASE_API_URL + "/" + uri).openConnection(); conn.setDoOutput(true); return getBrokerReturnJson(conn); }
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.ja va 2 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(); } }
From source file:game.Clue.JerseyClient.java
public void sendPUT(String name) { System.out.println("SendPUT method called"); try {/*from w w w . j a v a 2s.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:game.Clue.JerseyClient.java
public void sendPOST() { System.out.println("POST method called"); try {//from w w w . j av a2s. c o m JSONObject jsonObject = new JSONObject("{player:Brian}"); URL url = new URL( "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/game/"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); //setDoOutput(true); connection.setRequestProperty("POST", "application/json"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); System.out.println(jsonObject.toString()); out.write("{" + jsonObject.toString()); System.out.println("Sent PUT message to server"); out.close(); } catch (Exception e) { System.out.println("\nError while calling REST POST Service"); System.out.println(e); } }