List of usage examples for java.net HttpURLConnection setDoInput
public void setDoInput(boolean doinput)
From source file:com.ejisto.modules.dao.remote.BaseRemoteDao.java
private HttpURLConnection openConnection(String requestPath, String method) throws IOException { String destination = serverAddress + defaultIfEmpty(requestPath, "/"); log.log(Level.FINEST, "url destination: " + destination); HttpURLConnection connection = (HttpURLConnection) new URL(destination).openConnection(); connection.setDoInput(true); connection.setDoOutput(true);/*from w ww . j av a 2 s .c o m*/ if (method != null) { connection.setRequestMethod(method.toUpperCase()); } connection.connect(); return connection; }
From source file:com.flozano.socialauth.util.HttpUtil.java
/** * * @param urlStr/*from w w w.j a v a 2s . co m*/ * the URL String * @param requestMethod * Method type * @param params * Parameters to pass in request * @param header * Header parameters * @param inputStream * Input stream of image * @param fileName * Image file name * @param fileParamName * Image Filename parameter. It requires in some provider. * @return Response object * @throws SocialAuthException */ public static Response doHttpRequest(final String urlStr, final String requestMethod, final Map<String, String> params, final Map<String, String> header, final InputStream inputStream, final String fileName, final String fileParamName, Optional<ConnectionSettings> connectionSettings) throws SocialAuthException { HttpURLConnection conn; try { URL url = new URL(urlStr); if (proxyObj != null) { conn = (HttpURLConnection) url.openConnection(proxyObj); } else { conn = (HttpURLConnection) url.openConnection(); } connectionSettings.ifPresent(settings -> settings.apply(conn)); if (requestMethod.equalsIgnoreCase(MethodType.POST.toString()) || requestMethod.equalsIgnoreCase(MethodType.PUT.toString())) { conn.setDoOutput(true); } conn.setDoInput(true); conn.setInstanceFollowRedirects(true); if (timeoutValue > 0) { LOG.debug("Setting connection timeout : " + timeoutValue); conn.setConnectTimeout(timeoutValue); } if (requestMethod != null) { conn.setRequestMethod(requestMethod); } if (header != null) { for (String key : header.keySet()) { conn.setRequestProperty(key, header.get(key)); } } // If use POST or PUT must use this OutputStream os = null; if (inputStream != null) { if (requestMethod != null && !MethodType.GET.toString().equals(requestMethod) && !MethodType.DELETE.toString().equals(requestMethod)) { LOG.debug(requestMethod + " request"); String boundary = "----Socialauth-posting" + System.currentTimeMillis(); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); boundary = "--" + boundary; os = conn.getOutputStream(); DataOutputStream out = new DataOutputStream(os); write(out, boundary + "\r\n"); if (fileParamName != null) { write(out, "Content-Disposition: form-data; name=\"" + fileParamName + "\"; filename=\"" + fileName + "\"\r\n"); } else { write(out, "Content-Disposition: form-data; filename=\"" + fileName + "\"\r\n"); } write(out, "Content-Type: " + "multipart/form-data" + "\r\n\r\n"); int b; while ((b = inputStream.read()) != -1) { out.write(b); } // out.write(imageFile); write(out, "\r\n"); Iterator<Map.Entry<String, String>> entries = params.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); write(out, boundary + "\r\n"); write(out, "Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n"); // write(out, // "Content-Type: text/plain;charset=UTF-8 \r\n\r\n"); LOG.debug(entry.getValue()); out.write(entry.getValue().getBytes("UTF-8")); write(out, "\r\n"); } write(out, boundary + "--\r\n"); write(out, "\r\n"); } } conn.connect(); } catch (Exception e) { throw new SocialAuthException(e); } return new Response(conn); }
From source file:com.mobile.natal.natalchart.NetworkUtilities.java
/** * Send a file via HTTP POST with basic authentication. * * @param context the context to use./* w ww . j a v a 2s.c o m*/ * @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 if something goes wrong. */ public static String sendFilePost(Context context, 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()); // } // }); urlStr = urlStr + "?name=" + file.getName(); 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/octet-stream"); // conn.setRequestProperty("Content-Length", "" + fileSize); // conn.setRequestProperty("Connection", "Keep-Alive"); if (user != null && password != null && user.trim().length() > 0 && password.trim().length() > 0) { 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(); int responseCode = conn.getResponseCode(); return getMessageForCode(context, responseCode, context.getResources().getString(R.string.file_upload_completed_properly)); } catch (Exception e) { throw e; } finally { if (wr != null) wr.close(); if (fis != null) fis.close(); if (conn != null) conn.disconnect(); } }
From source file:MyWeatherService.java
String getWeatherFromInternet(String location) { String temperature = "", condition = "", weatherString; URL url;/* w w w . ja v a 2 s .c o m*/ if (location != null && !location.equals("")) { try { url = new URL(WEATHER_UNDERGROUND_URL + location + ".json"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String oneLineFromInternet; String wholeReplyFromInternet = ""; while ((oneLineFromInternet = reader.readLine()) != null) { wholeReplyFromInternet += oneLineFromInternet + " "; } JSONObject jsonObject = new JSONObject(wholeReplyFromInternet); JSONObject current_observation = jsonObject.getJSONObject("current_observation"); temperature = current_observation.getString(TEMP_F); condition = current_observation.getString(CONDITION); } catch (JSONException | IOException e) { e.printStackTrace(); } weatherString = temperature + (char) 0x00B0 + "F " + condition; } else { weatherString = "It's dark at night."; } return weatherString; }
From source file:gsi.twitter.StreetLocator.java
/** * Sends a request to the specified URL and obtains the result from the sever. * * @param url The URL to connect to//from ww w.java 2s . co m * @return the server response * @throws IOException */ private String getResult(URL url) throws IOException { // Log.d("Locator", url.toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); InputStream is = conn.getInputStream(); String result = toString(is); return result; }
From source file:com.juick.android.Utils.java
public static Bitmap downloadImage(String url) { try {/*ww w . j ava 2s. c o m*/ URL imgURL = new URL(url); HttpURLConnection conn = (HttpURLConnection) imgURL.openConnection(); conn.setDoInput(true); conn.connect(); return BitmapFactory.decodeStream(conn.getInputStream()); } catch (Exception e) { Log.e("downloadImage", e.toString()); } return null; }
From source file:it.openyoureyes.test.panoramio.Panoramio.java
private Bitmap downloadFile(String url) { Bitmap bmImg = null;/*from w ww . j av a2s .c om*/ URL myFileUrl = null; if (Util.isEmpty(url)) return null; try { myFileUrl = new URL(url); } catch (MalformedURLException e) { e.printStackTrace(); } try { HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); // BitmapFactory.Options op=new BitmapFactory.Options(); // op.inSampleSize = 3; bmImg = BitmapFactory.decodeStream(is);// ,null,op); conn.disconnect(); } catch (IOException e) { e.printStackTrace(); } return bmImg; }
From source file:libraryjava.parseJSON.java
/** * Bitmap/* w w w .ja v a 2 s. c o m*/ * @param urll * @return Bitmap */ public Bitmap doInBackground(String urll) { StrictMode(); try { URL url = new URL(urll); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input); return myBitmap; } catch (Exception ex) { return null; } }
From source file:br.bireme.tb.URLS.java
/** * Given an url, loads its content (POST - method) * @param url url to be loaded// w ww .j a v a 2 s . c om * @param urlParameters post parameters * @return an array with the real location of the page (in case of redirect) * and its content. * @throws IOException */ public static String[] loadPagePost(final URL url, final String urlParameters) throws IOException { if (url == null) { throw new NullPointerException("url"); } if (urlParameters == null) { throw new NullPointerException("urlParameters"); } final String encodedParams = URLEncoder.encode(urlParameters, DEFAULT_ENCODING); //System.out.print("loading page (POST): [" + url + "] params: " + urlParameters); //Create connection final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(encodedParams.getBytes().length)); //.getBytes(DEFAULT_ENCODING).length)); connection.setRequestProperty("Content-Language", "pt-BR"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { wr.write(encodedParams.getBytes(DEFAULT_ENCODING)); //wr.writeBytes(urlParameters); wr.flush(); } //Get Response final StringBuffer response = new StringBuffer(); try (final BufferedReader rd = new BufferedReader( new InputStreamReader(connection.getInputStream(), DEFAULT_ENCODING))) { while (true) { final String line = rd.readLine(); if (line == null) { break; } response.append(line); response.append('\n'); } } connection.disconnect(); return new String[] { url.toString() + "?" + urlParameters, response.toString() }; }
From source file:com.example.android.networkconnect.DownloadUrl.java
public InputStream downloadUrl(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect();/*ww w. jav a2s. c o m*/ InputStream stream = conn.getInputStream(); return stream; }