List of usage examples for java.net URL openConnection
public URLConnection openConnection() throws java.io.IOException
From source file:GetItemList.java
/** * Retrieve the contents of a URL/*from ww w. ja v a 2s . co m*/ * */ public static String getPage(String path) throws Exception { // Create the URL from the given path URL url = new URL(path); // We won't bother checking that everything's okay URLConnection url_conn = url.openConnection(); // Create a reader for the input stream BufferedReader read = new BufferedReader(new InputStreamReader(url_conn.getInputStream())); // read through each line and separate with the EOL string String out = ""; String line = ""; while ((line = read.readLine()) != null) { out += line + EOL_URL; } // Be sure to tidy up read.close(); // Return the contents of the URL return out; }
From source file:com.baidu.api.client.core.DownloadUtil.java
/** * Download the file pointed by the url and return the content as byte array. * * @param strUrl The Url to be downloaded. * @param connectTimeout Connect timeout in milliseconds. * @param readTimeout Read timeout in milliseconds. * @param maxFileSize Max file size in BYTE. * @return The file content as byte array. */// w ww . j av a 2 s .com public static byte[] downloadFile(String strUrl, int connectTimeout, int readTimeout, int maxFileSize) { InputStream in = null; try { URL url = new URL(strUrl); // URL? URLConnection ucon = url.openConnection(); ucon.setConnectTimeout(connectTimeout); ucon.setReadTimeout(readTimeout); ucon.connect(); if (ucon.getContentLength() > maxFileSize) { String msg = "File " + strUrl + " size [" + ucon.getContentLength() + "] too large, download stoped."; throw new ClientInternalException(msg); } if (ucon instanceof HttpURLConnection) { HttpURLConnection httpCon = (HttpURLConnection) ucon; if (httpCon.getResponseCode() > 399) { String msg = "Failed to download file " + strUrl + " server response " + httpCon.getResponseMessage(); throw new ClientInternalException(msg); } } in = ucon.getInputStream(); // ? byte[] byteBuf = new byte[BUFFER_SIZE]; byte[] ret = null; int count, total = 0; // ?? while ((count = in.read(byteBuf, total, BUFFER_SIZE - total)) > 0) { total += count; if (total + 124 >= BUFFER_SIZE) break; } if (total < BUFFER_SIZE - 124) { ret = ArrayUtils.subarray(byteBuf, 0, total); } else { ByteArrayOutputStream bos = new ByteArrayOutputStream(MATERIAL_SIZE); count = total; total = 0; do { bos.write(byteBuf, 0, count); total += count; if (total > maxFileSize) { String msg = "File " + strUrl + " size exceed [" + maxFileSize + "] download stoped."; throw new ClientInternalException(msg); } } while ((count = in.read(byteBuf)) > 0); ret = bos.toByteArray(); } if (ret.length < MIN_SIZE) { String msg = "File " + strUrl + " size [" + maxFileSize + "] too small."; throw new ClientInternalException(msg); } return ret; } catch (IOException e) { String msg = "Failed to download file " + strUrl + " msg=" + e.getMessage(); throw new ClientInternalException(msg); } finally { try { if (in != null) in.close(); } catch (IOException e) { // ? System.out.println("Exception while close url - " + e.getMessage()); } } }
From source file:com.binil.pushnotification.ServerUtil.java
/** * Issue a POST request to the server.//from w w w .j ava 2s . c o m * * @param endpoint POST address. * @param params request parameters. * @throws java.io.IOException propagated from POST. */ private static void post(String endpoint, Map<String, Object> params) throws IOException, JSONException { URL url = new URL(endpoint); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Cache-Control", "no-cache"); urlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); urlConnection.setRequestProperty("Accept-Encoding", "gzip,deflate"); urlConnection.setRequestProperty("Accept", "*/*"); urlConnection.setDoOutput(true); JSONObject json = new JSONObject(params); String body = json.toString(); urlConnection.setFixedLengthStreamingMode(body.length()); try { OutputStream os = urlConnection.getOutputStream(); os.write(body.getBytes("UTF-8")); os.close(); } catch (Exception e) { e.printStackTrace(); } finally { int status = urlConnection.getResponseCode(); String connectionMsg = urlConnection.getResponseMessage(); urlConnection.disconnect(); if (status != HttpURLConnection.HTTP_OK) { Log.wtf(TAG, connectionMsg); throw new IOException("Post failed with error code " + status); } } }
From source file:com.fun.util.TesseractUtil.java
/** * url?// w w w. ja v a 2 s . co m * * @param url * @return * @throws IOException */ private static File getFileFromUrl(URL url) throws IOException { File tmpImage = File.createTempFile("tesseract-ocr-download", null); InputStream in = url.openConnection().getInputStream(); FileOutputStream fos = new FileOutputStream(tmpImage); byte[] buf = new byte[1024]; int len = 0; while ((len = in.read(buf)) != -1) { fos.write(buf, 0, len); } fos.flush(); fos.close(); return tmpImage; }
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 ww w .ja va2s .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:eu.scape_project.pit.util.FileUtils.java
/** * Read file of URL into file./*from w w w. java 2 s .c om*/ * @param url URL where the input file is located * @param ext * @return Result file * @throws IOException */ public static File urlToFile(URL url, String ext) throws IOException { File fOut = null; fOut = getTmpFile("fromurl", "." + ext); URLConnection uc = url.openConnection(); logger.info("ContentType: " + uc.getContentType()); InputStream in = uc.getInputStream(); org.apache.commons.io.FileUtils.copyInputStreamToFile(in, fOut); logger.info("File of length " + fOut.length() + " created from URL " + url.toString()); in.close(); return fOut; }
From source file:Main.java
public static String UdatePlayerBT(String userName, String device) { String retStr = ""; try {//from w w w . ja v a 2 s .c o m URL url = new URL("http://" + IP_ADDRESS + "/RiddleQuizApp/ServerSide/PostaviBTdevice.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(15000); conn.setReadTimeout(10000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); Log.e("http", "por1"); JSONObject data = new JSONObject(); data.put("username", userName); data.put("bt_device", device); Log.e("http", "por3"); Uri.Builder builder = new Uri.Builder().appendQueryParameter("action", data.toString()); String query = builder.build().getEncodedQuery(); Log.e("http", "por4"); OutputStream os = conn.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); bw.write(query); Log.e("http", "por5"); bw.flush(); bw.close(); os.close(); int responseCode = conn.getResponseCode(); Log.e("http", String.valueOf(responseCode)); if (responseCode == HttpURLConnection.HTTP_OK) { retStr = inputStreamToString(conn.getInputStream()); } else retStr = String.valueOf("Error: " + responseCode); Log.e("http", retStr); } catch (Exception e) { Log.e("http", "greska"); } return retStr; }
From source file:Main.java
public static String UpdateScore(String userName, int br) { String retStr = ""; try {/*from w w w . j a va 2s. co m*/ URL url = new URL("http://" + IP_ADDRESS + "/RiddleQuizApp/ServerSide/AzurirajHighScore.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(15000); conn.setReadTimeout(10000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); Log.e("http", "por1"); JSONObject data = new JSONObject(); data.put("username", userName); data.put("broj", br); Log.e("http", "por3"); Uri.Builder builder = new Uri.Builder().appendQueryParameter("action", data.toString()); String query = builder.build().getEncodedQuery(); Log.e("http", "por4"); OutputStream os = conn.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); bw.write(query); Log.e("http", "por5"); bw.flush(); bw.close(); os.close(); int responseCode = conn.getResponseCode(); Log.e("http", String.valueOf(responseCode)); if (responseCode == HttpURLConnection.HTTP_OK) { retStr = inputStreamToString(conn.getInputStream()); } else retStr = String.valueOf("Error: " + responseCode); Log.e("http", retStr); } catch (Exception e) { Log.e("http", "greska"); } return retStr; }
From source file:com.arellomobile.android.push.utils.NetworkUtils.java
public static NetworkResult makeRequest(Map<String, Object> data, String methodName) throws Exception { NetworkResult result = new NetworkResult(500, null); OutputStream connectionOutput = null; InputStream inputStream = null; try {/* www. j a va 2 s. c om*/ String urlString = NetworkUtils.BASE_URL + methodName; if (useSSL) urlString = NetworkUtils.BASE_URL_SECURE + methodName; URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setDoOutput(true); JSONObject innerRequestJson = new JSONObject(); for (String key : data.keySet()) { innerRequestJson.put(key, data.get(key)); } JSONObject requestJson = new JSONObject(); requestJson.put("request", innerRequestJson); connection.setRequestProperty("Content-Length", String.valueOf(requestJson.toString().getBytes().length)); connectionOutput = connection.getOutputStream(); connectionOutput.write(requestJson.toString().getBytes()); connectionOutput.flush(); connectionOutput.close(); inputStream = new BufferedInputStream(connection.getInputStream()); ByteArrayOutputStream dataCache = new ByteArrayOutputStream(); // Fully read data byte[] buff = new byte[1024]; int len; while ((len = inputStream.read(buff)) >= 0) { dataCache.write(buff, 0, len); } // Close streams dataCache.close(); String jsonString = new String(dataCache.toByteArray()).trim(); Log.w(TAG, "PushWooshResult: " + jsonString); JSONObject resultJSON = new JSONObject(jsonString); result.setData(resultJSON); result.setCode(resultJSON.getInt("status_code")); } finally { if (null != inputStream) { inputStream.close(); } if (null != connectionOutput) { connectionOutput.close(); } } return result; }
From source file:com.netsteadfast.greenstep.util.FSUtils.java
/** * get MIME-TYPE // www . j a v a 2s. c o m * Using java.net.URL * * @param file * @return * @throws Exception */ public static String getMimeType4URL(File file) throws IOException, MalformedURLException, Exception { String mimeType = ""; if (file == null || !file.exists() || file.isDirectory()) { return mimeType; } URL url = new URL(file.getPath()); URLConnection urlConnection = url.openConnection(); mimeType = urlConnection.getContentType(); return mimeType; }