List of usage examples for java.net HttpURLConnection setDoInput
public void setDoInput(boolean doinput)
From source file:de.fu_berlin.inf.dpp.netbeans.feedback.FileSubmitter.java
/** * Tries to upload the given file to the given HTTP server (via POST * method)./*from w ww .j a v a2s . c o m*/ * * @param file * the file to upload * @param url * the URL of the server, that is supposed to handle the file * @param monitor * a monitor to report progress to * @throws IOException * if an I/O error occurs * */ public static void uploadFile(final File file, final String url, IProgressMonitor monitor) throws IOException { final String CRLF = "\r\n"; final String doubleDash = "--"; final String boundary = generateBoundary(); HttpURLConnection connection = null; OutputStream urlConnectionOut = null; FileInputStream fileIn = null; if (monitor == null) monitor = new NullProgressMonitor(); int contentLength = (int) file.length(); if (contentLength == 0) { log.warn("file size of file " + file.getAbsolutePath() + " is 0 or the file does not exist"); return; } monitor.beginTask("Uploading file " + file.getName(), contentLength); try { URL connectionURL = new URL(url); if (!"http".equals(connectionURL.getProtocol())) throw new IOException("only HTTP protocol is supported"); connection = (HttpURLConnection) connectionURL.openConnection(); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setReadTimeout(TIMEOUT); connection.setConnectTimeout(TIMEOUT); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); String contentDispositionLine = "Content-Disposition: form-data; name=\"" + file.getName() + "\"; filename=\"" + file.getName() + "\"" + CRLF; String contentTypeLine = "Content-Type: application/octet-stream; charset=ISO-8859-1" + CRLF; String contentTransferEncoding = "Content-Transfer-Encoding: binary" + CRLF; contentLength += 2 * boundary.length() + contentDispositionLine.length() + contentTypeLine.length() + contentTransferEncoding.length() + 4 * CRLF.length() + 3 * doubleDash.length(); connection.setFixedLengthStreamingMode(contentLength); connection.connect(); urlConnectionOut = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(urlConnectionOut, "US-ASCII"), true); writer.append(doubleDash).append(boundary).append(CRLF); writer.append(contentDispositionLine); writer.append(contentTypeLine); writer.append(contentTransferEncoding); writer.append(CRLF); writer.flush(); fileIn = new FileInputStream(file); byte[] buffer = new byte[8192]; for (int read = 0; (read = fileIn.read(buffer)) > 0;) { if (monitor.isCanceled()) return; urlConnectionOut.write(buffer, 0, read); monitor.worked(read); } urlConnectionOut.flush(); writer.append(CRLF); writer.append(doubleDash).append(boundary).append(doubleDash).append(CRLF); writer.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { log.debug("uploaded file " + file.getAbsolutePath() + " to " + connectionURL.getHost()); return; } throw new IOException("failed to upload file " + file.getAbsolutePath() + connectionURL.getHost() + " [" + connection.getResponseMessage() + "]"); } finally { IOUtils.closeQuietly(fileIn); IOUtils.closeQuietly(urlConnectionOut); if (connection != null) connection.disconnect(); monitor.done(); } }
From source file:com.mebigfatguy.polycasso.URLFetcher.java
/** * retrieve arbitrary data found at a specific url * - either http or file urls/*from w w w . j a va 2 s . com*/ * for http requests, sets the user-agent to mozilla to avoid * sites being cranky about a java sniffer * * @param url the url to retrieve * @param proxyHost the host to use for the proxy * @param proxyPort the port to use for the proxy * @return a byte array of the content * * @throws IOException the site fails to respond */ public static byte[] fetchURLData(String url, String proxyHost, int proxyPort) throws IOException { HttpURLConnection con = null; InputStream is = null; try { URL u = new URL(url); if (url.startsWith("file://")) { is = new BufferedInputStream(u.openStream()); } else { Proxy proxy; if (proxyHost != null) { proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); } else { proxy = Proxy.NO_PROXY; } con = (HttpURLConnection) u.openConnection(proxy); con.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6"); con.addRequestProperty("Accept-Charset", "UTF-8"); con.addRequestProperty("Accept-Language", "en-US,en"); con.addRequestProperty("Accept", "text/html,image/*"); con.setDoInput(true); con.setDoOutput(false); con.connect(); is = new BufferedInputStream(con.getInputStream()); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); return baos.toByteArray(); } finally { IOUtils.closeQuietly(is); if (con != null) { con.disconnect(); } } }
From source file:org.csware.ee.utils.Tools.java
public static String GetDataByPost(String httpUrl, String parMap) { try {/* w w w .ja v a 2 s .c o m*/ URL url = new URL(httpUrl);// HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("POST"); // ? connection.setRequestProperty("Accept", "application/json"); // ?? connection.setRequestProperty("Content-Type", "application/json"); // ???? connection.connect(); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8? out.append(parMap); out.flush(); out.close(); // ?? int length = (int) connection.getContentLength();// ? InputStream is = connection.getInputStream(); if (length != -1) { byte[] data = new byte[length]; byte[] temp = new byte[1024]; int readLen = 0; int destPos = 0; while ((readLen = is.read(temp)) > 0) { System.arraycopy(temp, 0, data, destPos, readLen); destPos += readLen; } String result = new String(data, "UTF-8"); // utf-8? return result; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("aa: " + e.getMessage()); } return "error"; // ? }
From source file:org.csware.ee.utils.Tools.java
public static String reqByPost(String path) { String info = ""; try {//from w ww . j a v a 2 s. co m // URL URL url = new URL(path); // HttpURLConnection HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // ?Input?output?Cache urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); /** ?method=post */ urlConn.setRequestMethod("POST"); urlConn.setRequestProperty("Connection", "Keep-Alive"); urlConn.setRequestProperty("Charset", "utf-8"); InputStream in = urlConn.getInputStream(); try { byte[] buffer = new byte[65536]; ByteArrayOutputStream bos = new ByteArrayOutputStream(); int readLength = in.read(buffer); long totalLength = 0; while (readLength >= 0) { bos.write(buffer, 0, readLength); totalLength = totalLength + readLength; readLength = in.read(buffer); } info = bos.toString(); } finally { if (in != null) try { in.close(); } catch (Exception e) { e.printStackTrace(); } } // urlConn.setConnectTimeout(5 * 1000); // urlConn.connect(); } catch (Exception ex) { ex.printStackTrace(); return null; } return info.replaceAll("\r\n", " "); }
From source file:com.madgag.android.lazydrawables.gravatar.GravatarBitmapDownloader.java
private InputStream downloadStreamFor(String gravatarId) { Log.d(TAG, "downloadStreamFor " + gravatarId); try {//from w w w . ja va2 s .c om URL aURL = new URL("http://www.gravatar.com/avatar/" + encode(gravatarId) + "?s=" + size + "&d=mm"); HttpURLConnection conn = (HttpURLConnection) aURL.openConnection(); conn.setDoInput(true); conn.connect(); return conn.getInputStream(); } catch (IOException ioe) { Log.e(TAG, "downloadGravatar " + gravatarId, ioe); throw new RuntimeException(ioe); } }
From source file:gov.nasa.arc.geocam.geocam.HttpPost.java
public static HttpURLConnection createConnection(String url, String username, String password) throws IOException { boolean useAuth = !password.equals(""); // force SSL if useAuth=true (would send password unencrypted otherwise) boolean useSSL = useAuth || url.startsWith("https"); Log.d("HttpPost", "password: " + password); Log.d("HttpPost", "useSSL: " + useSSL); if (useSSL) { if (!url.startsWith("https")) { // replace http: with https: -- this will obviously screw // up if input is something other than http so don't do that :) url = "https:" + url.substring(5); }//w w w . j a v a 2s .c o m // would rather not do this, need to check if there's still a problem // with our ssl certificates on NASA servers. try { DisableSSLCertificateCheckUtil.disableChecks(); } catch (GeneralSecurityException e) { throw new IOException("HttpPost - disable ssl: " + e); } } HttpURLConnection conn; try { if (useSSL) { conn = (HttpsURLConnection) (new URL(url)).openConnection(); } else { conn = (HttpURLConnection) (new URL(url)).openConnection(); } } catch (IOException e) { throw new IOException("HttpPost - IOException: " + e); } if (useAuth) { // add pre-emptive http basic authentication. using // homebrew version -- early versions of android // authenticator have problems and this is easy. String userpassword = username + ":" + password; String encodedAuthorization = Base64.encode(userpassword.getBytes()); conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization); } conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(true); return conn; }
From source file:com.bjorsond.android.timeline.sync.ServerUploader.java
protected static void uploadFile(String locationFilename, String saveFilename) { System.out.println("saving " + locationFilename + "!! "); if (!saveFilename.contains(".")) saveFilename = saveFilename + Utilities.getExtension(locationFilename); if (!fileExistsOnServer(saveFilename)) { HttpURLConnection connection = null; DataOutputStream outputStream = null; String pathToOurFile = locationFilename; String urlServer = "http://folk.ntnu.no/bjornava/upload/upload.php"; // String urlServer = "http://timelinegamified.appspot.com/upload.php"; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024 * 1024; try {/*w w w. ja v a 2s.co m*/ FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile)); URL url = new URL(urlServer); connection = (HttpURLConnection) url.openConnection(); // Allow Inputs & Outputs connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); // Enable POST method connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + saveFilename + "\"" + lineEnd); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Read file bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { outputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } outputStream.writeBytes(lineEnd); outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) int serverResponseCode = connection.getResponseCode(); String serverResponseMessage = connection.getResponseMessage(); fileInputStream.close(); outputStream.flush(); outputStream.close(); System.out.println("Server response: " + serverResponseCode + " Message: " + serverResponseMessage); } catch (Exception ex) { //Exception handling } } else { System.out.println("image exists on server"); } }
From source file:com.krayzk9s.imgurholo.tools.LoadImageAsync.java
@Override protected Bitmap doInBackground(Void... voids) { try {/*w ww . ja v a 2 s . c om*/ URL url; if (imageData.getJSONObject().has(ImgurHoloActivity.IMAGE_DATA_COVER)) url = new URL("http://imgur.com/" + imageData.getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_COVER) + ".png"); else url = new URL(imageData.getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_LINK)); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); return BitmapFactory.decodeStream(input); } catch (JSONException e) { Log.e("Error!", e.toString()); } catch (IOException e) { Log.e("Error!", e.toString()); } catch (OutOfMemoryError e) { Log.e("Error!", e.toString()); } return null; }
From source file:com.hippo.httpclient.JsonPoster.java
@Override public void onBeforeConnect(HttpURLConnection conn) throws Exception { super.onBeforeConnect(conn); conn.setDoOutput(true);//from www . j a v a 2s .c om conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); }
From source file:net.terryyiu.emailservice.providers.AbstractEmailServiceProvider.java
private HttpURLConnection createConnection() throws IOException { URL url = new URL(getServiceUrl()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true);//from w w w. j a v a 2 s . c o m connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setUseCaches(false); modifyConnection(connection); return connection; }