List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:org.devnexus.aerogear.HttpRestProvider.java
private void addBodyRequest(HttpURLConnection urlConnection, byte[] data) throws IOException { urlConnection.setDoOutput(true);/*from ww w.jav a 2s. c o m*/ if (data != null) { OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); out.write(data); out.flush(); } }
From source file:com.neoteric.starter.metrics.report.elastic.ElasticsearchReporter.java
private void closeConnection(HttpURLConnection connection) throws IOException { connection.getOutputStream().close(); connection.disconnect();/*from ww w . java2 s . c o m*/ // we have to call this, otherwise out HTTP data does not get send, even though close()/disconnect was called // Ceterum censeo HttpUrlConnection esse delendam if (connection.getResponseCode() != HttpStatus.OK.value()) { LOGGER.error("Reporting returned code {} {}: {}", connection.getResponseCode(), connection.getResponseMessage()); } }
From source file:si.mazi.rescu.HttpTemplate.java
/** * Requests JSON via an HTTP POST/*from w ww . ja va2s . c o m*/ * * * @param urlString A string representation of a URL * @param returnType The required return type * @param requestBody The contents of the request body * @param httpHeaders Any custom header values (application/json is provided automatically) * @param method Http method (usually GET or POST) * @param contentType the mime type to be set as the value of the Content-Type header * @param exceptionType * @return String - the fetched JSON String */ public <T> T executeRequest(String urlString, Class<T> returnType, String requestBody, Map<String, String> httpHeaders, HttpMethod method, String contentType, Class<? extends RuntimeException> exceptionType) { log.debug("Executing {} request at {}", method, urlString); log.trace("Request body = {}", requestBody); log.trace("Request headers = {}", httpHeaders); AssertUtil.notNull(urlString, "urlString cannot be null"); AssertUtil.notNull(httpHeaders, "httpHeaders should not be null"); httpHeaders.put("Accept", "application/json"); if (contentType != null) { httpHeaders.put("Content-Type", contentType); } try { int contentLength = requestBody == null ? 0 : requestBody.length(); HttpURLConnection connection = configureURLConnection(method, urlString, httpHeaders, contentLength); if (contentLength > 0) { // Write the request body connection.getOutputStream().write(requestBody.getBytes(CHARSET_UTF_8)); } String responseEncoding = getResponseEncoding(connection); int httpStatus = connection.getResponseCode(); log.debug("Request http status = {}", httpStatus); if (httpStatus != 200) { String httpBody = readInputStreamAsEncodedString(connection.getErrorStream(), responseEncoding); log.trace("Http call returned {}; response body:\n{}", httpStatus, httpBody); if (exceptionType != null) { throw JSONUtils.getJsonObject(httpBody, exceptionType, objectMapper); } else { throw new HttpStatusException("HTTP status code not 200", httpStatus, httpBody); } } InputStream inputStream = connection.getInputStream(); // Get the data String responseString = readInputStreamAsEncodedString(inputStream, responseEncoding); log.trace("Response body: {}", responseString); return JSONUtils.getJsonObject(responseString, returnType, objectMapper); } catch (MalformedURLException e) { throw new HttpException("Problem " + method + "ing -- malformed URL: " + urlString, e); } catch (IOException e) { throw new HttpException("Problem " + method + "ing (IO)", e); } }
From source file:com.testmax.util.HttpUtil.java
public int postFormdata(String myurl, String param, String xml) { HttpURLConnection httpConn = null; URL url;// w w w . j a va 2 s .c om int rest = -1; try { url = new URL(myurl); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestProperty("content-type", "text/xml; charset=utf-8"); httpConn.setDoOutput(true); OutputStream os = httpConn.getOutputStream(); BufferedWriter osw = new BufferedWriter(new OutputStreamWriter(os)); osw.write(xml); osw.flush(); osw.close(); rest = httpConn.getResponseCode(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return rest; }
From source file:com.huixueyun.tifenwang.api.net.HttpEngine.java
/** * http urlconnection?//from ww w.j av a 2 s. c o m * * @param paramsMap ?? * @param model ? * @param paramUrl ?? * @param type ? * @param <T> * @return ApiResponse? * @throws IOException */ public <T> T postConnectionHandle(Map<String, String> paramsMap, String model, String paramUrl, String type) throws IOException { String data = joinParams(paramsMap, type); // ? L.e(data); HttpURLConnection connection = getConnection(paramUrl); connection.setRequestProperty("Content-Length", String.valueOf(data.getBytes().length)); connection.connect(); OutputStream os = connection.getOutputStream(); os.write(data.getBytes()); os.flush(); if (connection.getResponseCode() == 200) { // ??? InputStream is = connection.getInputStream(); // ? ByteArrayOutputStream baos = new ByteArrayOutputStream(); // ? int len = 0; // byte buffer[] = new byte[1024]; // ?? while ((len = is.read(buffer)) != -1) { // ??os baos.write(buffer, 0, len); } // ? is.close(); baos.close(); connection.disconnect(); // final String result = new String(baos.toByteArray()); ApiResponse apiResponse; try { apiResponse = ApiModel.getInstance().getApiResponse(model, result); } catch (Exception e) { apiResponse = null; } return (T) apiResponse; } else { connection.disconnect(); return null; } }
From source file:costumetrade.common.sms.SMSActor.java
/** * HttpURLConnectionpost???// w w w. j av a 2s . co m */ private String sendPostRequestByForm(String path, String params) { HttpURLConnection conn = null; InputStream inStream = null; try { URL url = new URL(path); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST");// ??? conn.setDoOutput(true);// ?? conn.setDoInput(true); conn.getOutputStream().write(params.getBytes());// ? inStream = conn.getInputStream(); return IOUtils.toString(inStream, StandardCharsets.UTF_8); } catch (Exception e) { throw new RuntimeException("??", e); } finally { IOUtils.closeQuietly(inStream); if (conn != null) { conn.disconnect(); } } }
From source file:gr.uoc.nlp.opinion.analysis.suggestion.ElasticSearchIntegration.java
/** * * @param query// w w w . j a v a 2 s . c o m * @return */ public double executeQuery(String query) { double score = 0.0; try { String url = elasticSearchQueryURI; //open connection URL obj = new URL(url); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); //write data to socket try (OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream())) { out.write(query); out.close(); } String json = ""; String line = ""; BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); //get response while ((line = in.readLine()) != null) { json = json + line + " "; } // System.out.println(json); //transfor response to JSONObject JSONObject jsonObj = new JSONObject(json); try { //get max_score score = jsonObj.getJSONObject("hits").getDouble("max_score"); } catch (JSONException ex) { score = 0.0; } in.close(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException ex) { Logger.getLogger(ElasticSearchIntegration.class.getName()).log(Level.SEVERE, null, ex); } return score; }
From source file:com.threewks.analytics.client.AnalyticsClient.java
/** * Post JSON a URL. Ignore (but log) any errors. * //from w w w . j a va 2 s .c om * @param url the URL to post the data to. * @param json the JSON data to post. */ void postJson(String url, String json) { PrintWriter writer = null; try { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setDoOutput(true); connection.setRequestProperty(API_KEY_HEADER, apiKey); connection.setRequestProperty(CONTENT_TYPE_HEADER, JSON_CONTENT_TYPE); writer = new PrintWriter(connection.getOutputStream(), true); writer.append(json); writer.close(); int responseCode = connection.getResponseCode(); if (responseCode != 200) { logger.warning(String.format( "Analytics server returned HTTP response code: %s when posting data to url: %s", responseCode, url)); } } catch (Exception e) { logger.warning(String.format("Error sending data to url: %s, error: %s", url, e.getMessage())); } finally { IOUtils.closeQuietly(writer); } }
From source file:ict.servlet.UploadToServer.java
public static int upLoad2Server(String sourceFileUri) { String upLoadServerUri = "http://vbacdu.ddns.net:8080/WBS/newjsp.jsp"; // String [] string = sourceFileUri; String fileName = sourceFileUri; int serverResponseCode = 0; HttpURLConnection conn = null; DataOutputStream dos = null;/*ww w .j a v a2s. c o m*/ DataInputStream inStream = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String responseFromServer = ""; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { return 0; } try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("uploaded_file", fileName); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\"" + lineEnd); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); // create a buffer of maximum size bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); m_log.info("Upload file to server" + "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); // close streams m_log.info("Upload file to server" + fileName + " File is written"); fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { // ex.printStackTrace(); m_log.error("Upload file to server" + "error: " + ex.getMessage(), ex); } catch (Exception e) { // e.printStackTrace(); } //this block will give the response of upload link /* try { BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { m_log.info("Huzza" + "RES Message: " + line); } rd.close(); } catch (IOException ioex) { m_log.error("Huzza" + "error: " + ioex.getMessage(), ioex); }*/ return serverResponseCode; // like 200 (Ok) }
From source file:com.base2.kagura.core.authentication.RestAuthentication.java
public InputStream httpPost(String suffix, HashMap<String, String> values) { try {//from www .j ava2 s .com URL obj = new URL(url + "/" + suffix); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); String data = new ObjectMapper().writeValueAsString(values); con.setRequestProperty("Content-Type", "application/json"); con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(data); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); if (responseCode != 200) throw new Exception("Got error code: " + responseCode); return con.getInputStream(); } catch (Exception e) { e.printStackTrace(); return null; } }