List of usage examples for java.net HttpURLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:com.chiorichan.util.WebUtils.java
public static boolean sendTracking(String category, String action, String label) { String url = "http://www.google-analytics.com/collect"; try {// www . jav a 2 s . c om URL urlObj = new URL(url); HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); con.setRequestMethod("POST"); String urlParameters = "v=1&tid=UA-60405654-1&cid=" + Loader.getClientId() + "&t=event&ec=" + category + "&ea=" + action + "&el=" + label; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); Loader.getLogger().fine("Analytics Response [" + category + "]: " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return true; } catch (IOException e) { return false; } }
From source file:com.screenslicer.common.CommonUtil.java
public static String post(String uri, String recipient, String postData) { HttpURLConnection conn = null; try {//from www . j a va2 s.co m postData = Crypto.encode(postData, recipient); conn = (HttpURLConnection) new URL(uri).openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setConnectTimeout(0); conn.setRequestProperty("Content-Type", "application/json"); byte[] bytes = postData.getBytes("utf-8"); conn.setRequestProperty("Content-Length", String.valueOf(bytes.length)); OutputStream os = conn.getOutputStream(); os.write(bytes); conn.connect(); if (conn.getResponseCode() == 205) { return NOT_BUSY; } if (conn.getResponseCode() == 423) { return BUSY; } return Crypto.decode(IOUtils.toString(conn.getInputStream(), "utf-8"), recipient); } catch (Exception e) { Log.exception(e); } return ""; }
From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java
/** * Upload ontology content on specified dataset. Graph used is the default * one except if specified/*from w ww . j ava 2 s . co m*/ * * @param ontology * @param datasetName * @param graphName * @throws IOException * @throws HttpException */ public static void uploadOntology(InputStream ontology, String datasetName, @Nullable String graphName) throws IOException, HttpException { graphName = Strings.emptyToNull(graphName); logger.info("upload ontology in dataset: " + datasetName + " graph:" + Strings.nullToEmpty(graphName)); boolean createGraph = (graphName != null) ? true : false; String dataSetEncoded = URLEncoder.encode(datasetName, "UTF-8"); String graphEncoded = createGraph ? URLEncoder.encode(graphName, "UTF-8") : null; URL url = new URL(HOST + '/' + dataSetEncoded + "/data" + (createGraph ? "?graph=" + graphEncoded : "")); final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); String boundary = "------------------" + System.currentTimeMillis() + Long.toString(Math.round(Math.random() * 1000)); httpConnection.setUseCaches(false); httpConnection.setRequestMethod("POST"); httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); httpConnection.setRequestProperty("Connection", "keep-alive"); httpConnection.setRequestProperty("Cache-Control", "no-cache"); // set content httpConnection.setDoOutput(true); final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream()); out.write(BOUNDARY_DECORATOR + boundary + EOL); out.write("Content-Disposition: form-data; name=\"files[]\"; filename=\"ontology.owl\"" + EOL); out.write("Content-Type: application/octet-stream" + EOL + EOL); out.write(CharStreams.toString(new InputStreamReader(ontology))); out.write(EOL + BOUNDARY_DECORATOR + boundary + BOUNDARY_DECORATOR + EOL); out.close(); // handle HTTP/HTTPS strange behaviour httpConnection.connect(); httpConnection.disconnect(); // handle response switch (httpConnection.getResponseCode()) { case HttpURLConnection.HTTP_CREATED: checkState(createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage()); break; case HttpURLConnection.HTTP_OK: checkState(!createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage()); break; default: throw new HttpException( httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage()); } }
From source file:net.mutil.util.HttpUtil.java
public static String connServerForResultPost(String strUrl, HashMap<String, String> entityMap) throws ClientProtocolException, IOException { String strResult = ""; URL url = new URL(HttpUtil.getPCURL() + strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); StringBuilder entitySb = new StringBuilder(""); Object[] entityKeys = entityMap.keySet().toArray(); for (int i = 0; i < entityKeys.length; i++) { String key = (String) entityKeys[i]; if (i == 0) { entitySb.append(key + "=" + entityMap.get(key)); } else {/*from www . j av a2 s . c o m*/ entitySb.append("&" + key + "=" + entityMap.get(key)); } } byte[] entity = entitySb.toString().getBytes("UTF-8"); System.out.println(url.toString() + entitySb.toString()); conn.setConnectTimeout(5000); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(entity.length)); conn.getOutputStream().write(entity); if (conn.getResponseCode() == 200) { InputStream inputstream = conn.getInputStream(); StringBuffer buffer = new StringBuffer(); byte[] b = new byte[4096]; for (int n; (n = inputstream.read(b)) != -1;) { buffer.append(new String(b, 0, n)); } strResult = buffer.toString(); } return strResult; }
From source file:com.apptentive.android.sdk.comm.ApptentiveClient.java
private static ApptentiveHttpResponse performMultipartFilePost(Context context, String oauthToken, String uri, String postBody, StoredFile storedFile) { Log.d("Performing multipart request to %s", uri); ApptentiveHttpResponse ret = new ApptentiveHttpResponse(); if (storedFile == null) { Log.e("StoredFile is null. Unable to send."); return ret; }/*from w w w . java 2s. com*/ int bytesRead; int bufferSize = 4096; byte[] buffer; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = UUID.randomUUID().toString(); HttpURLConnection connection; DataOutputStream os = null; InputStream is = null; try { is = context.openFileInput(storedFile.getLocalFilePath()); // Set up the request. URL url = new URL(uri); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setConnectTimeout(DEFAULT_HTTP_CONNECT_TIMEOUT); connection.setReadTimeout(DEFAULT_HTTP_SOCKET_TIMEOUT); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); connection.setRequestProperty("Authorization", "OAuth " + oauthToken); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("X-API-Version", API_VERSION); connection.setRequestProperty("User-Agent", getUserAgentString()); StringBuilder requestText = new StringBuilder(); // Write form data requestText.append(twoHyphens).append(boundary).append(lineEnd); requestText.append("Content-Disposition: form-data; name=\"message\"").append(lineEnd); requestText.append("Content-Type: text/plain").append(lineEnd); requestText.append(lineEnd); requestText.append(postBody); requestText.append(lineEnd); // Write file attributes. requestText.append(twoHyphens).append(boundary).append(lineEnd); requestText.append(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"", storedFile.getFileName())).append(lineEnd); requestText.append("Content-Type: ").append(storedFile.getMimeType()).append(lineEnd); requestText.append(lineEnd); Log.d("Post body: " + requestText); // Open an output stream. os = new DataOutputStream(connection.getOutputStream()); // Write the text so far. os.writeBytes(requestText.toString()); try { // Write the actual file. buffer = new byte[bufferSize]; while ((bytesRead = is.read(buffer, 0, bufferSize)) > 0) { os.write(buffer, 0, bytesRead); } } catch (IOException e) { Log.d("Error writing file bytes to HTTP connection.", e); ret.setBadPayload(true); throw e; } os.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); os.close(); ret.setCode(connection.getResponseCode()); ret.setReason(connection.getResponseMessage()); // TODO: These streams may not be ready to read now. Put this in a new thread. // Read the normal response. InputStream nis = null; ByteArrayOutputStream nbaos = null; try { Log.d("Sending file: " + storedFile.getLocalFilePath()); nis = connection.getInputStream(); nbaos = new ByteArrayOutputStream(); byte[] eBuf = new byte[1024]; int eRead; while (nis != null && (eRead = nis.read(eBuf, 0, 1024)) > 0) { nbaos.write(eBuf, 0, eRead); } ret.setContent(nbaos.toString()); } catch (IOException e) { Log.w("Can't read return stream.", e); } finally { Util.ensureClosed(nis); Util.ensureClosed(nbaos); } // Read the error response. InputStream eis = null; ByteArrayOutputStream ebaos = null; try { eis = connection.getErrorStream(); ebaos = new ByteArrayOutputStream(); byte[] eBuf = new byte[1024]; int eRead; while (eis != null && (eRead = eis.read(eBuf, 0, 1024)) > 0) { ebaos.write(eBuf, 0, eRead); } if (ebaos.size() > 0) { ret.setContent(ebaos.toString()); } } catch (IOException e) { Log.w("Can't read error stream.", e); } finally { Util.ensureClosed(eis); Util.ensureClosed(ebaos); } Log.d("HTTP " + connection.getResponseCode() + ": " + connection.getResponseMessage() + ""); Log.v(ret.getContent()); } catch (FileNotFoundException e) { Log.e("Error getting file to upload.", e); } catch (MalformedURLException e) { Log.e("Error constructing url for file upload.", e); } catch (SocketTimeoutException e) { Log.w("Timeout communicating with server."); } catch (IOException e) { Log.e("Error executing file upload.", e); } finally { Util.ensureClosed(is); Util.ensureClosed(os); } return ret; }
From source file:com.pubkit.network.PubKitNetwork.java
public static JSONObject sendPost(String apiKey, JSONObject jsonObject) { URL url;/*from ww w . j ava2s . c om*/ HttpURLConnection connection = null; try { //Create connection url = new URL(PUBKIT_API_URL); String encodedData = jsonObject.toString(); byte[] postDataBytes = jsonObject.toString().getBytes("UTF-8"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Length", "" + String.valueOf(postDataBytes.length)); connection.setRequestProperty("api_key", apiKey); connection.setUseCaches(false); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(encodedData);//set data wr.flush(); //Get Response InputStream inputStream = connection.getErrorStream(); //first check for error. if (inputStream == null) { inputStream = connection.getInputStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder response = new StringBuilder(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } wr.close(); rd.close(); String responseString = response.toString(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { return new JSONObject("{'error':'" + responseString + "'}"); } else { try { return new JSONObject(responseString); } catch (JSONException e) { Log.e("PUBKIT", "Error parsing data", e); } } } catch (Exception e) { Log.e("PUBKIT", "Network exception:", e); } finally { if (connection != null) { connection.disconnect(); } } return null; }
From source file:com.androidex.volley.toolbox.HurlStack.java
/** * Perform a multipart request on a connection * /* w w w .j a v a2 s. co m*/ * @param connection * The Connection to perform the multi part request * @param request * The params to add to the Multi Part request * The files to upload * @throws ProtocolException */ private static void setConnectionParametersForMultipartRequest(HttpURLConnection connection, Request<?> request) throws IOException, ProtocolException { final String charset = ((MultiPartRequest<?>) request).getProtocolCharset(); final int curTime = (int) (System.currentTimeMillis() / 1000); final String boundary = BOUNDARY_PREFIX + curTime; connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty(HEADER_CONTENT_TYPE, String.format(CONTENT_TYPE_MULTIPART, charset, curTime)); Map<String, MultiPartParam> multipartParams = ((MultiPartRequest<?>) request).getMultipartParams(); Map<String, String> filesToUpload = ((MultiPartRequest<?>) request).getFilesToUpload(); if (((MultiPartRequest<?>) request).isFixedStreamingMode()) { int contentLength = getContentLengthForMultipartRequest(boundary, multipartParams, filesToUpload); connection.setFixedLengthStreamingMode(contentLength); } else { connection.setChunkedStreamingMode(0); } // Modified end ProgressListener progressListener; progressListener = (ProgressListener) request; PrintWriter writer = null; try { OutputStream out = connection.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(out, charset), true); for (String key : multipartParams.keySet()) { MultiPartParam param = multipartParams.get(key); writer.append(boundary).append(CRLF) .append(String.format(HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA, key)) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + param.contentType).append(CRLF) .append(CRLF).append(param.value).append(CRLF).flush(); } for (String key : filesToUpload.keySet()) { File file = new File(filesToUpload.get(key)); if (!file.exists()) { throw new IOException(String.format("File not found: %s", file.getAbsolutePath())); } if (file.isDirectory()) { throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath())); } writer.append(boundary).append(CRLF) .append(String.format( HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA + SEMICOLON_SPACE + FILENAME, key, file.getName())) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + CONTENT_TYPE_OCTET_STREAM) .append(CRLF).append(HEADER_CONTENT_TRANSFER_ENCODING + COLON_SPACE + BINARY).append(CRLF) .append(CRLF).flush(); BufferedInputStream input = null; try { FileInputStream fis = new FileInputStream(file); int transferredBytes = 0; int totalSize = (int) file.length(); input = new BufferedInputStream(fis); int bufferLength = 0; byte[] buffer = new byte[1024]; while ((bufferLength = input.read(buffer)) > 0) { out.write(buffer, 0, bufferLength); transferredBytes += bufferLength; progressListener.onProgress(transferredBytes, totalSize); } out.flush(); // Important! Output cannot be closed. Close of // writer will close // output as well. } finally { if (input != null) try { input.close(); } catch (IOException ex) { ex.printStackTrace(); } } writer.append(CRLF).flush(); // CRLF is important! It indicates // end of binary // boundary. } // End of multipart/form-data. writer.append(boundary + BOUNDARY_PREFIX).append(CRLF).flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { writer.close(); } } }
From source file:com.volley.air.toolbox.HurlStack.java
/** * Perform a multipart request on a connection * //from w w w .j a va2 s . c o m * @param connection * The Connection to perform the multi part request * @param request * The params to add to the Multi Part request * The files to upload * @throws ProtocolException */ private static void setConnectionParametersForMultipartRequest(HttpURLConnection connection, Request<?> request) throws IOException, ProtocolException { final String charset = ((MultiPartRequest<?>) request).getProtocolCharset(); final int curTime = (int) (System.currentTimeMillis() / 1000); final String boundary = BOUNDARY_PREFIX + curTime; connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty(HEADER_CONTENT_TYPE, String.format(CONTENT_TYPE_MULTIPART, charset, curTime)); Map<String, MultiPartParam> multipartParams = ((MultiPartRequest<?>) request).getMultipartParams(); Map<String, String> filesToUpload = ((MultiPartRequest<?>) request).getFilesToUpload(); if (((MultiPartRequest<?>) request).isFixedStreamingMode()) { int contentLength = getContentLengthForMultipartRequest(boundary, multipartParams, filesToUpload); connection.setFixedLengthStreamingMode(contentLength); } else { connection.setChunkedStreamingMode(0); } // Modified end ProgressListener progressListener; progressListener = (ProgressListener) request; PrintWriter writer = null; try { OutputStream out = connection.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(out, charset), true); for (Entry<String, MultiPartParam> entry : multipartParams.entrySet()) { MultiPartParam param = entry.getValue(); writer.append(boundary).append(CRLF) .append(String.format(HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA, entry.getKey())) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + param.contentType).append(CRLF) .append(CRLF).append(param.value).append(CRLF).flush(); } for (Entry<String, String> entry : filesToUpload.entrySet()) { File file = new File(entry.getValue()); if (!file.exists()) { throw new IOException(String.format("File not found: %s", file.getAbsolutePath())); } if (file.isDirectory()) { throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath())); } writer.append(boundary).append(CRLF) .append(String.format( HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA + SEMICOLON_SPACE + FILENAME, entry.getKey(), file.getName())) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + CONTENT_TYPE_OCTET_STREAM) .append(CRLF).append(HEADER_CONTENT_TRANSFER_ENCODING + COLON_SPACE + BINARY).append(CRLF) .append(CRLF).flush(); BufferedInputStream input = null; try { FileInputStream fis = new FileInputStream(file); int transferredBytes = 0; int totalSize = (int) file.length(); input = new BufferedInputStream(fis); int bufferLength; byte[] buffer = new byte[1024]; while ((bufferLength = input.read(buffer)) > 0) { out.write(buffer, 0, bufferLength); transferredBytes += bufferLength; progressListener.onProgress(transferredBytes, totalSize); } out.flush(); // Important! Output cannot be closed. Close of // writer will close // output as well. } finally { if (input != null) try { input.close(); } catch (IOException ex) { ex.printStackTrace(); } } writer.append(CRLF).flush(); // CRLF is important! It indicates // end of binary // boundary. } // End of multipart/form-data. writer.append(boundary + BOUNDARY_PREFIX).append(CRLF).flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { writer.close(); } } }
From source file:xqpark.ParkApi.java
/** * API?/*ww w .ja va 2 s .c om*/ * @param ?url * @return APIJSON? * @throws JSONException * @throws IOException * @throws ParseException */ public static JSONObject loadJSON(String url) throws JSONException { StringBuilder json = new StringBuilder(); try { URLEncoder.encode(url, "UTF-8"); URL urlObject = new URL(url); HttpURLConnection uc = (HttpURLConnection) urlObject.openConnection(); uc.setDoOutput(true);// URL uc.setDoInput(true);// URL uc.setUseCaches(false); uc.setRequestMethod("POST"); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8")); String inputLine = null; while ((inputLine = in.readLine()) != null) { json.append(inputLine); } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } JSONObject responseJson = new JSONObject(json.toString()); return responseJson; }
From source file:com.omertron.themoviedbapi.tools.WebBrowser.java
public static String request(URL url, String jsonBody, boolean isDeleteRequest) throws MovieDbException { StringWriter content = null;/* ww w . ja v a 2 s . co m*/ try { content = new StringWriter(); BufferedReader in = null; HttpURLConnection cnx = null; OutputStreamWriter wr = null; try { cnx = (HttpURLConnection) openProxiedConnection(url); // If we get a null connection, then throw an exception if (cnx == null) { throw new MovieDbException(MovieDbException.MovieDbExceptionType.CONNECTION_ERROR, "No HTTP connection could be made.", url); } if (isDeleteRequest) { cnx.setDoOutput(true); cnx.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); cnx.setRequestMethod("DELETE"); } sendHeader(cnx); if (StringUtils.isNotBlank(jsonBody)) { cnx.setDoOutput(true); wr = new OutputStreamWriter(cnx.getOutputStream()); wr.write(jsonBody); } readHeader(cnx); // http://stackoverflow.com/questions/4633048/httpurlconnection-reading-response-content-on-403-error if (cnx.getResponseCode() >= 400) { in = new BufferedReader(new InputStreamReader(cnx.getErrorStream(), getCharset(cnx))); } else { in = new BufferedReader(new InputStreamReader(cnx.getInputStream(), getCharset(cnx))); } String line; while ((line = in.readLine()) != null) { content.write(line); } } finally { if (wr != null) { wr.flush(); wr.close(); } if (in != null) { in.close(); } if (cnx instanceof HttpURLConnection) { ((HttpURLConnection) cnx).disconnect(); } } return content.toString(); } catch (IOException ex) { throw new MovieDbException(MovieDbException.MovieDbExceptionType.CONNECTION_ERROR, null, url, ex); } finally { if (content != null) { try { content.close(); } catch (IOException ex) { LOG.debug("Failed to close connection: " + ex.getMessage()); } } } }