List of usage examples for java.net HttpURLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:com.ab.network.toolbox.HurlStack.java
@SuppressWarnings("deprecation") /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: // This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { // Prepare output. There is no need to set Content-Length explicitly, // since this is handled by HttpURLConnection using the size of the prepared // output stream. connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(postBody);/*from www.ja v a 2 s . co m*/ out.close(); } break; case Method.GET: // Not necessary to set the request method because connection defaults to GET but // being explicit here. connection.setRequestMethod("GET"); break; case Method.DELETE: connection.setRequestMethod("DELETE"); break; case Method.POST: connection.setRequestMethod("POST"); addBodyIfExists(connection, request); break; case Method.PUT: connection.setRequestMethod("PUT"); addBodyIfExists(connection, request); break; default: throw new IllegalStateException("Unknown method type."); } }
From source file:com.wudoumi.batter.volley.toolbox.HurlStack.java
@SuppressWarnings("deprecation") /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case RequestType.DEPRECATED_GET_OR_POST: // This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { // Prepare output. There is no need to set Content-Length explicitly, // since this is handled by HttpURLConnection using the size of the prepared // output stream. connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(postBody);/* ww w .j a v a2 s . c o m*/ out.close(); } break; case RequestType.GET: // Not necessary to set the request method because connection defaults to GET but // being explicit here. connection.setRequestMethod("GET"); break; case RequestType.DELETE: connection.setRequestMethod("DELETE"); break; case RequestType.POST: connection.setRequestMethod("POST"); addBodyIfExists(connection, request); break; case RequestType.PUT: connection.setRequestMethod("PUT"); addBodyIfExists(connection, request); break; default: throw new IllegalStateException("Unknown method type."); } }
From source file:com.volley.android.toolbox.HurlStack.java
@SuppressWarnings("deprecation") /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Request.Method.DEPRECATED_GET_OR_POST: // This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { // Prepare output. There is no need to set Content-Length explicitly, // since this is handled by HttpURLConnection using the size of the prepared // output stream. connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(postBody);/*from w w w.j av a2 s . c om*/ out.close(); } break; case Request.Method.GET: // Not necessary to set the request method because connection defaults to GET but // being explicit here. connection.setRequestMethod("GET"); break; case Request.Method.DELETE: connection.setRequestMethod("DELETE"); break; case Request.Method.POST: connection.setRequestMethod("POST"); addBodyIfExists(connection, request); break; case Request.Method.PUT: connection.setRequestMethod("PUT"); addBodyIfExists(connection, request); break; default: throw new IllegalStateException("Unknown method type."); } }
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;//from w w w. j a v a 2 s . 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.autonavi.gxdtaojin.toolbox.HurlStack.java
@SuppressWarnings("deprecation") /* package */static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: // This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { // Prepare output. There is no need to set Content-Length explicitly, // since this is handled by HttpURLConnection using the size of the prepared // output stream. connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(postBody);/*from w w w. j ava2 s. c o m*/ out.close(); } break; case Method.GET: // Not necessary to set the request method because connection defaults to GET but // being explicit here. connection.setRequestMethod("GET"); break; case Method.DELETE: connection.setRequestMethod("DELETE"); break; case Method.POST: connection.setRequestMethod("POST"); addBodyIfExists(connection, request); break; case Method.PUT: connection.setRequestMethod("PUT"); addBodyIfExists(connection, request); break; default: throw new IllegalStateException("Unknown method type."); } }
From source file:com.sunchenbin.store.feilong.core.net.URLConnectionUtil.java
/** * Prepare connection.//from w ww.j av a 2 s . com * * @param httpURLConnection * the http url connection * @param httpRequest * the http request * @param useConnectionConfig * the use connection config * @throws IOException * the IO exception * @since 1.4.0 * @see "org.springframework.http.client.SimpleClientHttpRequestFactory#prepareConnection(HttpURLConnection, String)" */ private static void prepareConnection(HttpURLConnection httpURLConnection, HttpRequest httpRequest, ConnectionConfig useConnectionConfig) throws IOException { HttpMethodType httpMethodType = httpRequest.getHttpMethodType(); // ?HttpUrlConnectionconnectTimeout httpURLConnection.setConnectTimeout(useConnectionConfig.getConnectTimeout()); httpURLConnection.setReadTimeout(useConnectionConfig.getReadTimeout()); httpURLConnection.setRequestMethod(httpMethodType.getMethod().toUpperCase());//?,? java.net.ProtocolException: Invalid HTTP method: get httpURLConnection.setDoOutput(HttpMethodType.POST == httpMethodType); Map<String, String> headerMap = httpRequest.getHeaderMap(); if (null != headerMap) { for (Map.Entry<String, String> entry : headerMap.entrySet()) { httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue()); } } }
From source file:eu.geopaparazzi.library.network.NetworkUtilities.java
/** * Send a file via HTTP POST with basic authentication. * // w w w. j a v a 2s . c om * @param urlStr the server url to POST to. * @param file the file to send. * @param user the user or <code>null</code>. * @param password the password or <code>null</code>. * @return the return string from the POST. * @throws Exception */ public static String sendFilePost(String urlStr, File file, String user, String password) throws Exception { BufferedOutputStream wr = null; FileInputStream fis = null; HttpURLConnection conn = null; try { fis = new FileInputStream(file); long fileSize = file.length(); // Authenticator.setDefault(new Authenticator(){ // protected PasswordAuthentication getPasswordAuthentication() { // return new PasswordAuthentication("test", "test".toCharArray()); // } // }); conn = makeNewConnection(urlStr); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); // conn.setChunkedStreamingMode(0); conn.setUseCaches(true); // conn.setRequestProperty("Accept-Encoding", "gzip "); // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Type", "application/x-zip-compressed"); // conn.setRequestProperty("Content-Length", "" + fileSize); // conn.setRequestProperty("Connection", "Keep-Alive"); if (user != null && password != null) { conn.setRequestProperty("Authorization", getB64Auth(user, password)); } conn.connect(); wr = new BufferedOutputStream(conn.getOutputStream()); long bufferSize = Math.min(fileSize, maxBufferSize); if (GPLog.LOG) GPLog.addLogEntry(TAG, "BUFFER USED: " + bufferSize); byte[] buffer = new byte[(int) bufferSize]; int bytesRead = fis.read(buffer, 0, (int) bufferSize); long totalBytesWritten = 0; while (bytesRead > 0) { wr.write(buffer, 0, (int) bufferSize); totalBytesWritten = totalBytesWritten + bufferSize; if (totalBytesWritten >= fileSize) break; bufferSize = Math.min(fileSize - totalBytesWritten, maxBufferSize); bytesRead = fis.read(buffer, 0, (int) bufferSize); } wr.flush(); String responseMessage = conn.getResponseMessage(); if (GPLog.LOG) GPLog.addLogEntry(TAG, "POST RESPONSE: " + responseMessage); return responseMessage; } catch (Exception e) { e.printStackTrace(); throw e; } finally { if (wr != null) wr.close(); if (fis != null) fis.close(); if (conn != null) conn.disconnect(); } }
From source file:com.krawler.common.util.BaseStringUtil.java
public static String makeExternalRequest(String urlstr, String postdata) { String result = ""; try {/* ww w .ja va 2 s . com*/ URL url = new URL(urlstr); try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); DataOutputStream d = new DataOutputStream(conn.getOutputStream()); String data = postdata; OutputStreamWriter ow = new OutputStreamWriter(d); ow.write(data); ow.close(); BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder stringbufff = new StringBuilder(); while ((inputLine = input.readLine()) != null) { stringbufff.append(inputLine); } result = stringbufff.toString(); input.close(); } catch (IOException ex) { System.out.print(ex); } } catch (MalformedURLException ex) { System.out.print(ex); } finally { return result; } }
From source file:com.fota.Link.sdpApi.java
public static String getCtnInfo(String ncn) throws JDOMException { String resultStr = ""; String logData = ""; try {/*w w w .j ava 2 s . com*/ String cpId = PropUtil.getPropValue("sdp3g.id"); String cpPw = PropUtil.getPropValue("sdp3g.pw"); String authorization = cpId + ":" + cpPw; logData = "\r\n---------- Get Ctn Req Info start ----------\r\n"; logData += " getCtnRequestInfo - authorization : " + authorization; byte[] encoded = Base64.encodeBase64(authorization.getBytes()); authorization = new String(encoded); String contractType = "0"; String contractNum = ncn.substring(0, 9); String customerId = ncn.substring(10, ncn.length() - 1); JSONObject reqJObj = new JSONObject(); reqJObj.put("transactionid", ""); reqJObj.put("sequenceno", ""); reqJObj.put("userid", ""); reqJObj.put("screenid", ""); reqJObj.put("CONTRACT_NUM", contractNum); reqJObj.put("CUSTOMER_ID", customerId); reqJObj.put("CONTRACT_TYPE", contractType); authorization = "Basic " + authorization; String endPointUrl = PropUtil.getPropValue("sdp.oif555.url"); logData += "\r\n getCtnRequestInfo - endPointUrl : " + endPointUrl; logData += "\r\n getCtnRequestInfo - authorization(encode) : " + authorization; logData += "\r\n getCtnRequestInfo - Content-type : application/json"; logData += "\r\n getCtnRequestInfo - RequestMethod : POST"; logData += "\r\n getCtnRequestInfo - json : " + reqJObj.toString(); logData += "\r\n---------- Get Ctn Req Info end ----------"; logger.info(logData); // connection URL url = new URL(endPointUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", authorization); connection.setRequestProperty("Content-type", "application/json"); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); // output DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(reqJObj.toJSONString()); wr.flush(); wr.close(); // input BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine = ""; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONParser jsonParser = new JSONParser(); JSONObject respJsonObject = (JSONObject) jsonParser.parse(response.toString()); // String respTransactionId = (String) respJsonObject.get("transactionid"); // String respSequenceNo = (String) respJsonObject.get("sequenceno"); // String respReturnCode = (String) respJsonObject.get("returncode"); // String respReturnDescription = (String) respJsonObject.get("returndescription"); // String respErrorCode = (String) respJsonObject.get("errorcode"); // String respErrorDescription = (String) respJsonObject.get("errordescription"); String respCtn = (String) respJsonObject.get("ctn"); // String respSubStatus = (String) respJsonObject.get("sub_status"); // String respSubStatusDate = (String) respJsonObject.get("sub_status_date"); resultStr = respCtn; //resultStr = resValue; // resultStr = java.net.URLDecoder.decode(resultStr, "euc-kr"); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } return resultStr; }
From source file:com.aiven.seafox.controller.http.volley.toolbox.HurlStack.java
@SuppressWarnings("deprecation") /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: // This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { // Prepare output. There is no need to set Content-Length explicitly, // since this is handled by HttpURLConnection using the size of the prepared // output stream. connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(postBody);/*from w w w. j a v a 2s . c o m*/ out.close(); } break; case Method.GET: // Not necessary to set the request method because connection defaults to GET but // being explicit here. connection.setRequestMethod("GET"); break; case Request.Method.DELETE: connection.setRequestMethod("DELETE"); break; case Request.Method.POST: connection.setRequestMethod("POST"); addBodyIfExists(connection, request); break; case Method.PUT: connection.setRequestMethod("PUT"); addBodyIfExists(connection, request); break; case Method.HEAD: connection.setRequestMethod("HEAD"); break; case Method.OPTIONS: connection.setRequestMethod("OPTIONS"); break; case Method.TRACE: connection.setRequestMethod("TRACE"); break; case Method.PATCH: connection.setRequestMethod("PATCH"); addBodyIfExists(connection, request); break; default: throw new IllegalStateException("Unknown method type."); } }