List of usage examples for java.net HttpURLConnection connect
public abstract void connect() throws IOException;
From source file:com.expertiseandroid.lib.sociallib.utils.Utils.java
/** * Sends a POST request with an attached object * @param url the url that should be opened * @param params the body parameters/*from www . j av a2 s . c om*/ * @param attachment the object to be attached * @return the response * @throws IOException */ public static String postWithAttachment(String url, Map<String, String> params, Object attachment) throws IOException { String boundary = generateBoundaryString(10); URL servUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) servUrl.openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + SOCIALLIB); conn.setRequestMethod("POST"); String contentType = "multipart/form-data; boundary=" + boundary; conn.setRequestProperty("Content-Type", contentType); byte[] body = generatePostBody(params, attachment, boundary); conn.setDoOutput(true); conn.connect(); OutputStream out = conn.getOutputStream(); out.write(body); InputStream is = null; try { is = conn.getInputStream(); } catch (FileNotFoundException e) { is = conn.getErrorStream(); } catch (Exception e) { int statusCode = conn.getResponseCode(); Log.e("Response code", "" + statusCode); return conn.getResponseMessage(); } BufferedReader r = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String l; while ((l = r.readLine()) != null) sb.append(l).append('\n'); out.close(); is.close(); if (conn != null) conn.disconnect(); return sb.toString(); }
From source file:com.book.jtm.chap03.HttpClientDemo.java
public static void sendRequest(String method, String url) throws IOException { InputStream is = null;//from ww w. jav a 2s . c o m try { URL newUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) newUrl.openConnection(); // ?10 conn.setReadTimeout(10000); // 15 conn.setConnectTimeout(15000); // ?,GET"GET",post"POST" conn.setRequestMethod("GET"); // ?? conn.setDoInput(true); // ??,???? conn.setDoOutput(true); // Header conn.setRequestProperty("Connection", "Keep-Alive"); // ? List<NameValuePair> paramsList = new ArrayList<NameValuePair>(); paramsList.add(new BasicNameValuePair("username", "mr.simple")); paramsList.add(new BasicNameValuePair("pwd", "mypwd")); writeParams(conn.getOutputStream(), paramsList); // ? conn.connect(); is = conn.getInputStream(); // ? String result = convertStreamToString(is); Log.i("", "### : " + result); } finally { if (is != null) { is.close(); } } }
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. j a v a 2s .co m*/ 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:at.mukprojects.giphy4j.dao.HttpRequestSender.java
private Response send(HttpURLConnection connection) throws IOException { connection.connect(); if (connection.getResponseCode() != 200) { throw new IOException("Bad response! Code: " + connection.getResponseCode()); }/* w w w . ja va2 s .c om*/ Map<String, String> headers = new HashMap<String, String>(); for (String key : connection.getHeaderFields().keySet()) { headers.put(key, connection.getHeaderFields().get(key).get(0)); } String body = null; InputStream inputStream = null; try { inputStream = connection.getInputStream(); String encoding = connection.getContentEncoding(); encoding = encoding == null ? Giphy4JConstants.ENCODING : encoding; body = IOUtils.toString(inputStream, encoding); } catch (IOException e) { throw new IOException(e); } finally { if (inputStream != null) { inputStream.close(); } } if (body == null) { throw new IOException("Unparseable response body! \n {" + body + "}"); } Response response = new Response(headers, body); return response; }
From source file:br.eb.ime.pfc.controllers.WMSStyleImageServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//ww w .j a va2s.c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { InputStream in = null; try { URL url = new URL( "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2c/Download_font_awesome.svg/512px-Download_font_awesome.svg.png"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); in = conn.getInputStream(); byte[] data = IOUtils.toByteArray(in); response.getOutputStream().write(data); } catch (Exception e) { } finally { in.close(); } }
From source file:com.none.tom.simplerssreader.net.FeedDownloader.java
@SuppressWarnings("ConstantConditions") public static InputStream getInputStream(final Context context, final String feedUrl) { final ConnectivityManager manager = context.getSystemService(ConnectivityManager.class); final NetworkInfo info = manager.getActiveNetworkInfo(); if (info == null || !info.isConnected()) { ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK); LogUtils.logError("No network connection"); return null; }//from w w w . j ava2 s . c o m URL url; try { url = new URL(feedUrl); } catch (final MalformedURLException e) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_BAD_REQUEST, e); return null; } final boolean[] networkPrefs = DefaultSharedPrefUtils.getNetworkPreferences(context); final boolean useHttpTorProxy = networkPrefs[0]; final boolean httpsOnly = networkPrefs[1]; final boolean followRedir = networkPrefs[2]; for (int nrRedirects = 0;; nrRedirects++) { if (nrRedirects >= HTTP_NR_REDIRECTS_MAX) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_TOO_MANY_REDIRECTS); LogUtils.logError("Too many redirects"); return null; } HttpURLConnection conn = null; try { if (httpsOnly && url.getProtocol().equalsIgnoreCase("http")) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTPS_ONLY); LogUtils.logError("Attempting insecure connection"); return null; } if (useHttpTorProxy) { conn = (HttpURLConnection) url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(InetAddress.getByName(HTTP_PROXY_TOR_IP), HTTP_PROXY_TOR_PORT))); } else { conn = (HttpURLConnection) url.openConnection(); } conn.setRequestProperty("Accept-Charset", StandardCharsets.UTF_8.name()); conn.setConnectTimeout(HTTP_URL_DEFAULT_TIMEOUT); conn.setReadTimeout(HTTP_URL_DEFAULT_TIMEOUT); conn.connect(); final int responseCode = conn.getResponseCode(); switch (responseCode) { case HttpURLConnection.HTTP_OK: return getInputStream(conn.getInputStream()); case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: case HttpURLConnection.HTTP_SEE_OTHER: case HTTP_TEMP_REDIRECT: if (followRedir) { final String location = conn.getHeaderField("Location"); url = new URL(url, location); if (responseCode == HttpURLConnection.HTTP_MOVED_PERM) { SharedPrefUtils.updateSubscriptionUrl(context, url.toString()); } continue; } ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_FOLLOW_REDIRECT_DENIED); LogUtils.logError("Couldn't follow redirect"); return null; default: if (responseCode < 0) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_RESPONSE); LogUtils.logError("No valid HTTP response"); return null; } else if (responseCode >= 400 && responseCode <= 500) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_CLIENT); } else if (responseCode >= 500 && responseCode <= 600) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_SERVER); } else { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED); } LogUtils.logError("Error " + responseCode + ": " + conn.getResponseMessage()); return null; } } catch (final IOException e) { if ((e instanceof ConnectException && e.getMessage().equals("Network is unreachable")) || e instanceof SocketTimeoutException || e instanceof UnknownHostException) { ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK, e); } else { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED, e); } return null; } finally { if (conn != null) { conn.disconnect(); } } } }
From source file:edu.rit.chrisbitler.ritcraft.slackintegration.rtm.RTMClient.java
/** * Send a slack message to a channel via the web api * @param text The text to send to the channel * @param channel The channel ID to send it to (usually the relay channel) *//* w ww . j av a 2 s . com*/ public void sendSlackMessage(String text, String channel) { try { URL chat = new URL("https://slack.com/api/chat.postMessage?token=" + SlackIntegration.BOT_TOKEN + "&channel=" + channel + "&text=" + URLEncoder.encode(text, "UTF-8")); HttpURLConnection conn = (HttpURLConnection) chat.openConnection(); conn.connect(); conn.getContent(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.gson.util.HttpKit.java
/** * ?http?/* w w w .j a v a 2 s. c om*/ * @param url * @param method * @param headers * @return * @throws IOException */ private static HttpURLConnection initHttp(String url, String method, Map<String, String> headers) throws IOException { URL _url = new URL(url); HttpURLConnection http = (HttpURLConnection) _url.openConnection(); // http.setConnectTimeout(25000); // ? --?? http.setReadTimeout(25000); http.setRequestMethod(method); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"); if (null != headers && !headers.isEmpty()) { for (Entry<String, String> entry : headers.entrySet()) { http.setRequestProperty(entry.getKey(), entry.getValue()); } } http.setDoOutput(true); http.setDoInput(true); http.connect(); return http; }
From source file:com.krayzk9s.imgurholo.tools.LoadImageAsync.java
@Override protected Bitmap doInBackground(Void... voids) { try {/*from ww w . ja v a2s . 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:ar.com.zauber.common.image.impl.JREImageRetriver.java
/** @see ImageRetriver#retrive(URL) */ public final InputStream retrive(final URL url) throws IOException { Validate.notNull(url);/*from ww w .j a v a2s.c om*/ final URLConnection uc = url.openConnection(); if (uc instanceof HttpURLConnection) { final HttpURLConnection huc = (HttpURLConnection) uc; prepare(uc); huc.connect(); final String contentType = huc.getContentType(); if (contentType != null && contentType.length() > 0 && !huc.getContentType().trim().startsWith("image/")) { throw new RuntimeException("la URL no parece apuntar a una imagen "); } if (huc.getContentLength() > maxBytes) { throw new RuntimeException("la imagen pesa ms de " + maxBytes); } final InputStream is = uc.getInputStream(); return is; } else { throw new IllegalArgumentException("solo se soporta el protocolo " + " http"); } }