List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:com.scut.easyfe.network.kjFrame.http.HttpConnectStack.java
/** * body/*from w w w.j a v a 2 s .c o m*/ */ private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } }
From source file:connector.ISConnector.java
public static JSONObject processRequest(String servlet, byte[] query) { JSONObject response = null;//from w w w . j a va 2 s.c o m if (servlet != null && !servlet.startsWith("/")) servlet = "/" + servlet; try { // Establish HTTP connection with Identity Service URL url = new URL(CONTEXT_PATH + servlet); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //Create the form content try (OutputStream out = conn.getOutputStream()) { out.write(query); out.close(); } // Buffer the result into a string BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); conn.disconnect(); response = (JSONObject) new JSONParser().parse(sb.toString()); } catch (Exception e) { e.printStackTrace(); } return response; }
From source file:com.android.volley.stack.HurlStack.java
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true);//from w ww.j av a 2 s.com connection.addRequestProperty(HTTP.CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } }
From source file:Main.java
/** * Issue a POST request to the server.// ww w.ja va 2 s . co m * * @param endpoint * POST address. * @param params * request parameters. * * @throws IOException * propagated from POST. */ public static String post_t(String endpoint, Map<String, Object> params, String contentType) throws IOException { URL url; try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, Object>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, Object> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=').append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); 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", contentType); // 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); } // Get Response InputStream is = conn.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } rd.close(); return response.toString(); } finally { if (conn != null) { conn.disconnect(); } } }
From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java
private static String sendPOST(URL url, HttpURLConnection con, String body) throws IOException { con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/json"); con.setRequestProperty("Accept", "application/json"); con.setDoOutput(true);//from ww w .j a va 2s .co m DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); logger.log(Level.INFO, "Sending POST request to URL : {0}", url); int responseCode = con.getResponseCode(); logger.log(Level.INFO, "Response Code : {0}", responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder responseStr = new StringBuilder(); while ((inputLine = in.readLine()) != null) { responseStr.append(inputLine); } in.close(); return responseStr.toString(); }
From source file:cc.vileda.sipgatesync.api.SipgateApi.java
public static String getToken(final String username, final String password) { try {//from w w w . java2 s.c o m final HttpURLConnection urlConnection = getConnection("/authorization/token"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestMethod("POST"); JSONObject request = new JSONObject(); request.put("username", username); request.put("password", password); OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream()); Log.d("SipgateApi", request.getString("username")); wr.write(request.toString()); wr.flush(); StringBuilder sb = new StringBuilder(); int HttpResult = urlConnection.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader( new InputStreamReader(urlConnection.getInputStream(), "utf-8")); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); Log.d("SipgateApi", "" + sb.toString()); final JSONObject response = new JSONObject(sb.toString()); return response.getString("token"); } else { System.out.println(urlConnection.getResponseMessage()); } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.memetix.gun4j.GunshortenAPI.java
protected static JSONObject post(final String serviceUrl, final String paramsString) throws Exception { final URL url = new URL(serviceUrl); final HttpURLConnection uc = (HttpURLConnection) url.openConnection(); if (referrer != null) uc.setRequestProperty("referer", referrer); uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + ENCODING); uc.setRequestProperty("Accept-Charset", ENCODING); uc.setRequestMethod("POST"); uc.setDoOutput(true);/*from www.ja v a 2 s. co m*/ final PrintWriter pw = new PrintWriter(uc.getOutputStream()); pw.write(paramsString); pw.close(); uc.getOutputStream().close(); try { final int responseCode = uc.getResponseCode(); final String result = inputStreamToString(uc.getInputStream()); if (responseCode != 200) { throw new Exception("Error from Gunshorten API: " + result); } return parseJSON(result); } finally { uc.getInputStream().close(); if (uc.getErrorStream() != null) { uc.getErrorStream().close(); } } }
From source file:com.zf.util.Post_NetNew.java
public static String pn(Map<String, String> pams) throws Exception { if (null == pams) { return ""; }//from ww w . ja v a2 s . co m String strtmp = "url"; URL url = new URL(pams.get(strtmp)); pams.remove(strtmp); strtmp = "body"; String body = pams.get(strtmp); pams.remove(strtmp); strtmp = "POST"; if (StringUtils.isEmpty(body)) strtmp = "GET"; HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setRequestMethod(strtmp); for (String pam : pams.keySet()) { httpConn.setRequestProperty(pam, pams.get(pam)); } if ("POST".equals(strtmp)) { httpConn.setDoOutput(true); httpConn.setDoInput(true); DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream()); dos.writeBytes(body); dos.flush(); } int resultCode = httpConn.getResponseCode(); StringBuilder sb = new StringBuilder(); sb.append(resultCode).append("\n"); String readLine; InputStream stream; try { stream = httpConn.getInputStream(); } catch (Exception ignored) { stream = httpConn.getErrorStream(); } try { BufferedReader responseReader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); while ((readLine = responseReader.readLine()) != null) { sb.append(readLine).append("\n"); } } catch (Exception ignored) { } return sb.toString(); }
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 .j av a 2 s . co 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.gson.util.HttpKit.java
/** * @description // w ww .j a va2 s . c o m * ??: POST * @return : * @throws IOException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public static String post(String url, String params) throws KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException, IOException { HttpURLConnection http = null; if (isHttps(url)) { http = initHttps(url, _POST, null); } else { http = initHttp(url, _POST, null); } OutputStream out = http.getOutputStream(); out.write(params.getBytes(DEFAULT_CHARSET)); out.flush(); out.close(); InputStream in = http.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; StringBuffer bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } in.close(); if (http != null) { http.disconnect();// } return bufferRes.toString(); }