List of usage examples for java.net HttpURLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:it.unicaradio.android.gcm.GcmServerRpcCall.java
/** * @param url//from w w w . j a v a 2 s. co m * @param bytes * @return * @throws IOException * @throws ProtocolException */ private static HttpURLConnection setupConnection(URL url, byte[] bytes) throws IOException, ProtocolException { HttpURLConnection conn; conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); return conn; }
From source file:com.arthurpitman.common.HttpUtils.java
/** * Connects to an HTTP resource using the post method. * @param url the URL to connect to./*from w w w . ja v a 2 s .co m*/ * @param requestProperties optional request properties, <code>null</code> if not required. * @param postData the data to post. * @return the resulting {@link HttpURLConnection}. * @throws IOException */ public static HttpURLConnection connectPost(final String url, final RequestProperty[] requestProperties, final byte[] postData) throws IOException { // setup connection HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod(POST_METHOD); // send the post form connection.setFixedLengthStreamingMode(postData.length); addRequestProperties(connection, requestProperties); OutputStream outStream = connection.getOutputStream(); outStream.write(postData); outStream.close(); return connection; }
From source file:Main.java
static byte[] httpRequest(String url, byte[] requestBytes, int connectionTimeOutMs, int readTimeOutMs) { byte[] bArr = null; if (!(url == null || requestBytes == null)) { InputStream inputStream = null; HttpURLConnection urlConnection = null; try {//ww w .ja va 2s. c o m urlConnection = (HttpURLConnection) new URL(url).openConnection(); urlConnection.setDoOutput(true); urlConnection.setConnectTimeout(connectionTimeOutMs); urlConnection.setReadTimeout(readTimeOutMs); urlConnection.setFixedLengthStreamingMode(requestBytes.length); OutputStream outputStream = urlConnection.getOutputStream(); outputStream.write(requestBytes); outputStream.close(); if (urlConnection.getResponseCode() != 200) { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } if (urlConnection != null) { urlConnection.disconnect(); } } else { inputStream = urlConnection.getInputStream(); ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[16384]; while (true) { int chunkSize = inputStream.read(buffer); if (chunkSize < 0) { break; } else if (chunkSize > 0) { result.write(buffer, 0, chunkSize); } } bArr = result.toByteArray(); if (inputStream != null) { try { inputStream.close(); } catch (IOException e2) { } } if (urlConnection != null) { urlConnection.disconnect(); } } } catch (IOException e3) { if (inputStream != null) { try { inputStream.close(); } catch (IOException e4) { } } if (urlConnection != null) { urlConnection.disconnect(); } } catch (Throwable th) { if (inputStream != null) { try { inputStream.close(); } catch (IOException e5) { } } if (urlConnection != null) { urlConnection.disconnect(); } } } return bArr; }
From source file:com.google.android.gcm.demo.app.ServerUtilities.java
/** * Issue a POST request to the server.//from w w w.java 2 s . c om * * @param endpoint POST address. * @param params request parameters. * * @throws IOException propagated from POST. */ private static void post(String endpoint, Map<String, String> params) throws IOException { URL url; try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } JSONObject jsonObj = new JSONObject(params); String body = jsonObj.toString(); Log.v(TAG, "Posting '" + body + "' to " + url); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); // post the request OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); // handle the response int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } }
From source file:Main.java
/** * Uses http to post an XML String to a URL. * * @param url//from w w w .j av a 2 s. com * @param xmlString * @param return * @throws IOException * @throws UnknownHostException */ public static HttpURLConnection post(String url, String xmlString) throws IOException, UnknownHostException { // open connection URL urlObject = new URL(url); HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/xml; charset=\"utf-8\""); connection.setDoOutput(true); OutputStreamWriter outStream = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); outStream.write(xmlString); outStream.close(); return connection; }
From source file:Authentication.DinserverAuth.java
public static boolean Login(String nick, String pass, Socket socket) throws IOException { boolean logged = false; JSONObject authRequest = new JSONObject(); authRequest.put("username", nick); authRequest.put("auth_id", pass); String query = "http://127.0.0.1:5000/token"; URL url = new URL(query); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000);//from ww w .j ava 2s.c om conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); OutputStream os = conn.getOutputStream(); os.write(authRequest.toString().getBytes(Charset.forName("UTF-8"))); os.close(); String output = new String(); StringBuilder sb = new StringBuilder(); int HttpResult = conn.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { output = IOUtils.toString(new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8"))); } else { System.out.println(conn.getResponseMessage()); } JSONObject jsonObject = new JSONObject(output); logged = jsonObject.getBoolean("ok"); conn.disconnect(); if (logged) { if (DinserverMaster.addUser(nick, socket)) { System.out.println("User " + nick + " logged in"); } else { logged = false; } } return logged; }
From source file:Main.java
/** * Do an HTTP POST and return the data as a byte array. *//*from w w w .ja v a 2s .com*/ public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties) throws MalformedURLException, IOException { HttpURLConnection urlConnection = null; try { urlConnection = (HttpURLConnection) new URL(url).openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(data != null); urlConnection.setDoInput(true); if (requestProperties != null) { for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) { urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue()); } } urlConnection.connect(); if (data != null) { OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); out.write(data); out.close(); } InputStream in = new BufferedInputStream(urlConnection.getInputStream()); return convertInputStreamToByteArray(in); } catch (IOException e) { String details; if (urlConnection != null) { details = "; code=" + urlConnection.getResponseCode() + " (" + urlConnection.getResponseMessage() + ")"; } else { details = ""; } Log.e("ExoplayerUtil", "executePost: Request failed" + details, e); throw e; } finally { if (urlConnection != null) { urlConnection.disconnect(); } } }
From source file:Main.java
/** * Executes a post request using {@link HttpURLConnection}. * * @param url The request URL.// w w w . j a va 2s. c o m * @param data The request body, or null. * @param requestProperties Request properties, or null. * @return The response body. * @throws IOException If an error occurred making the request. */ // TODO: Remove this and use HttpDataSource once DataSpec supports inclusion of a POST body. public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties) throws IOException { HttpURLConnection urlConnection = null; try { urlConnection = (HttpURLConnection) new URL(url).openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(data != null); urlConnection.setDoInput(true); if (requestProperties != null) { for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) { urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue()); } } // Write the request body, if there is one. if (data != null) { OutputStream out = urlConnection.getOutputStream(); try { out.write(data); } finally { out.close(); } } // Read and return the response body. InputStream inputStream = urlConnection.getInputStream(); try { return toByteArray(inputStream); } finally { inputStream.close(); } } finally { if (urlConnection != null) { urlConnection.disconnect(); } } }
From source file:software.uncharted.util.HTTPUtil.java
public static String post(String urlToRead, String postData) { URL url;/*w ww. ja va2 s . co m*/ HttpURLConnection conn; try { url = new URL(urlToRead); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json"); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(postData); wr.flush(); wr.close(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; InputStream is = conn.getInputStream(); while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); return buffer.toString(); } catch (Exception e) { e.printStackTrace(); System.err.println("Failed to read URL: " + urlToRead + " <" + e.getMessage() + ">"); } return null; }
From source file:com.adanac.module.blog.api.HttpApiHelper.java
public static void baiduPush(int remain) { String pushUrl = DaoFactory.getDao(HtmlPageDao.class).findPushUrl(); if (pushUrl == null) { if (logger.isInfoEnabled()) { logger.info("all html page has been pushed!"); }/*from w w w . ja va 2 s.com*/ return; } if (remain <= 0) { if (logger.isInfoEnabled()) { logger.info("there has no remain[" + remain + "]!"); } return; } if (logger.isInfoEnabled()) { logger.info("find push url : " + pushUrl); } String url = "http://data.zz.baidu.com/urls?site=" + site + "&token=" + token; try { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/plain"); OutputStream outputStream = connection.getOutputStream(); outputStream.write(pushUrl.getBytes("UTF-8")); outputStream.write("\r\n".getBytes("UTF-8")); outputStream.flush(); int status = connection.getResponseCode(); if (logger.isInfoEnabled()) { logger.info("baidu-push response code : " + status); } if (status == HttpServletResponse.SC_OK) { String response = IOUtil.read(connection.getInputStream()); if (logger.isInfoEnabled()) { logger.info("baidu-push response : " + response); } JSONObject result = JSONObject.fromObject(response); if (result.getInt("success") >= 1) { DaoFactory.getDao(HtmlPageDao.class).updateIsPush(pushUrl); } else { logger.warn("push url failed : " + pushUrl); } baiduPush(result.getInt("remain")); } else { logger.error("baidu-push error : " + IOUtil.read(connection.getErrorStream())); } } catch (Exception e) { logger.error("baidu push failed ...", e); } }