public void makeRequest() { java.net.URL url; try { if (validateConnection()) { url = new URL(URL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(methodConnection); connection.setRequestProperty("Content-Type", TYPE_JSON); connection.setConnectTimeout(TIMEOUT); if ((methodConnection.equals(POST) || methodConnection.equals(PUT)) && params != null) configBody(params); if (headerParams != null) processHeader(); processReturn(); postExecute(response != null ? response.toString() : null); } else { error(new MessageResponse("Sem conexão com a internet", false)); } } catch (Exception e) { if (e instanceof ConnectTimeoutException || e instanceof ConnectException) messageResponse.setMsg("Problemas ao tentar conectar com o servidor."); else if (e instanceof NullPointerException) messageResponse.setMsg("Humm, algo de errado deve ter acontecido com o servidor."); else messageResponse.setMsg(e.getMessage()); error(messageResponse); } finally { if (connection != null) { connection.disconnect(); } } }
public static String submitPostData(String pos, String data) throws IOException { Log.v("req", data); URL url = new URL(urlPre + pos); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); configConnection(connection); if (sCookie != null && sCookie.length() > 0) { connection.setRequestProperty("Cookie", sCookie); } connection.connect(); // Send data DataOutputStream output = new DataOutputStream(connection.getOutputStream()); output.write(data.getBytes()); output.flush(); output.close(); // check Cookie String cookie = connection.getHeaderField("set-cookie"); if (cookie != null && !cookie.equals(sCookie)) { sCookie = cookie; } // Respond BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } connection.disconnect(); String res = sb.toString(); Log.v("res", res); return res; }
/* 发送request至博客的对应网址的method */ private String sendPost(String outString) { HttpURLConnection conn = null; String result = ""; URL url = null; try { url = new URL(path); conn = (HttpURLConnection) url.openConnection(); /* 允许Input、Output */ conn.setDoInput(true); conn.setDoOutput(true); /* 设定传送的method=POST */ conn.setRequestMethod("POST"); /* setRequestProperty */ conn.setRequestProperty("Content-Type", "text/xml"); conn.setRequestProperty("Charset", "UTF-8"); /* 送出request */ OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8"); out.write(outString); out.flush(); out.close(); /* 解析回传的XML内容 */ result = parseXML(conn.getInputStream()); conn.disconnect(); } catch (Exception e) { conn.disconnect(); e.printStackTrace(); showDialog("" + e); } return result; }
public String getWeatherData(String location) { HttpURLConnection con = null; InputStream is = null; try { con = (HttpURLConnection) (new URL(BASE_URL + location)).openConnection(); con.setRequestMethod("GET"); con.setDoInput(true); con.setDoOutput(true); con.connect(); // Let's read the response StringBuffer buffer = new StringBuffer(); is = con.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = br.readLine()) != null) buffer.append(line + "\r\n"); is.close(); con.disconnect(); return buffer.toString(); } catch (Throwable t) { t.printStackTrace(); } finally { try { is.close(); } catch (Throwable t) { } try { con.disconnect(); } catch (Throwable t) { } } return null; }
@Test public void shouldNotPostNodeWithInvalidPrimaryType() throws Exception { URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/invalidPrimaryType"); HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON); String payload = "{ \"properties\": {\"jcr:primaryType\": \"invalidType\", \"testProperty\": \"testValue\", \"multiValuedProperty\": [\"value1\", \"value2\"]}}"; connection.getOutputStream().write(payload.getBytes()); assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_BAD_REQUEST)); connection.disconnect(); postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/invalidPrimaryType"); connection = (HttpURLConnection) postUrl.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON); assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_NOT_FOUND)); connection.disconnect(); }
/** * @param file - the name of the file, as saved to the repo (including extension) * @return - the direct link * @throws NoSuchAlgorithmException - see md5 */ public static String getCreeperhostLink(String file) throws NoSuchAlgorithmException { if (currentmd5.isEmpty()) { currentmd5 = md5("mcepoch1" + getTime()); } String resolved = "http://repo.creeperhost.net/direct/FTB2/" + currentmd5 + "/" + file; HttpURLConnection connection = null; try { connection = (HttpURLConnection) new URL(resolved).openConnection(); } catch (MalformedURLException e1) { Logger.logError(e1.getMessage(), e1); } catch (IOException e1) { Logger.logError(e1.getMessage(), e1); } try { int retries = 1; while (connection.getResponseCode() != 200 && retries <= 3) { connection.disconnect(); resolved = "http://repo" + retries + ".creeperhost.net/direct/FTB2/" + currentmd5 + "/" + file; retries++; try { connection = (HttpURLConnection) new URL(resolved).openConnection(); } catch (MalformedURLException e) { Logger.logError(e.getMessage(), e); } catch (IOException e) { Logger.logError(e.getMessage(), e); } } } catch (IOException e) { Logger.logError(e.getMessage(), e); } connection.disconnect(); Logger.logInfo(resolved); return resolved; }
/** * Checks the file for corruption. * * @param file - File to check * @return - boolean representing if it is valid * @throws IOException */ public static boolean isValid(File file) throws IOException { String content = null; Scanner scanner = null; int retries = 1; try { HttpURLConnection connection = (HttpURLConnection) new URL("http://repo.creeperhost.net/md5/FTB2/" + file.getName()).openConnection(); while (connection.getResponseCode() != 200 && retries <= 3) { connection.disconnect(); connection = (HttpURLConnection) new URL("http://repo" + retries + ".creeperhost.net/md5/FTB2/" + file.getName()) .openConnection(); retries++; } scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); connection.disconnect(); } catch (java.net.UnknownHostException uhe) { Logger.logError(uhe.getMessage(), uhe); } catch (Exception ex) { Logger.logError(ex.getMessage(), ex); } finally { if (scanner != null) { scanner.close(); } } String result = fileMD5(file); Logger.logInfo(result); return content.equalsIgnoreCase(result); }
@Test public void shouldFailWholeTransactionIfOneNodeIsBad() throws Exception { URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/invalidNestedPost"); HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON); String payload = "{ \"properties\": {\"jcr:primaryType\": \"nt:unstructured\", \"testProperty\": \"testValue\", \"multiValuedProperty\": [\"value1\", \"value2\"]}," + " \"children\": { \"childNode\" : { \"properties\": {\"jcr:primaryType\": \"invalidType\"}}}}"; connection.getOutputStream().write(payload.getBytes()); assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_BAD_REQUEST)); connection.disconnect(); postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/invalidNestedPost?mode:depth=1"); connection = (HttpURLConnection) postUrl.openConnection(); // Make sure that we can retrieve the node with a GET connection.setDoOutput(true); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON); assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_NOT_FOUND)); connection.disconnect(); }
/** * gets the time from the creeperhost servers * * @return - the time in the DDMMYY format */ public static String getTime() { String content = null; Scanner scanner = null; int retries = 1; try { HttpURLConnection connection = (HttpURLConnection) new URL("http://repo.creeperhost.net/getdate").openConnection(); while (connection.getResponseCode() != 200 && retries <= 3) { connection.disconnect(); connection = (HttpURLConnection) new URL("http://repo" + retries + ".creeperhost.net/getdate").openConnection(); retries++; } scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); connection.disconnect(); } catch (java.net.UnknownHostException uhe) { Logger.logError(uhe.getMessage(), uhe); } catch (Exception ex) { Logger.logError(ex.getMessage(), ex); } finally { if (scanner != null) { scanner.close(); } } return content; }
public static HttpURLConnection download(final HttpURLConnection con, final File file) throws IOException { if (file.exists()) { con.setIfModifiedSince(file.lastModified()); con.connect(); if (con.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { log.fine("Using " + file.getName() + " from cache"); con.disconnect(); return con; } } log.fine("Downloading new " + file.getName()); final byte[] buffer = downloadBinary(con); if (!file.exists()) { file.createNewFile(); } if (file.exists() && (!file.canRead() || file.canWrite())) { file.setReadable(true); file.setWritable(true); } if (file.exists() && file.canRead() && file.canWrite()) { final FileOutputStream fos = new FileOutputStream(file); fos.write(buffer); fos.flush(); fos.close(); } file.setLastModified(con.getLastModified()); con.disconnect(); return con; }
@Override protected CollageRegionData performLoad() throws Exception { final File filesDir = CommonUtils.getCacheFileDir(); if (null == filesDir) { throw new DiskWriteException(); } final File outputFile = new File(filesDir, String.format(IMAGE_NAME, mCollageRegion.getId())); if (outputFile.exists() && !outputFile.delete()) { throw new DiskWriteException(); } final HttpURLConnection connection = (HttpURLConnection) new URL(mPost.getStandardResolutionImage().getUrl()).openConnection(); connection.setUseCaches(true); final int responseCode = connection.getResponseCode(); if (responseCode >= 300) { connection.disconnect(); throw new InternalServerException(); } CommonUtils.writeNetworkStreamToAnOtherStream( connection.getInputStream(), new FileOutputStream(outputFile)); connection.disconnect(); if (outputFile.exists()) { return new CollageRegionData(outputFile); } else { throw new DiskWriteException(); } }
/** * Does a HTTP/HTTPS HEADER request (currently used to check ex.fm links) * * @param urlString the complete url string to do the request with * @return a String containing the response of this request */ public static boolean httpHeaderRequest(String urlString) { URLConnection urlConnection; HttpURLConnection connection = null; try { URL url = new URL(urlString); urlConnection = url.openConnection(); if (urlConnection instanceof HttpURLConnection) { connection = (HttpURLConnection) urlConnection; } else { throw new MalformedURLException("Connection could not be cast to HttpUrlConnection"); } connection.setConnectTimeout(15000); connection.setReadTimeout(15000); connection.setRequestMethod("HEAD"); connection.setInstanceFollowRedirects(false); connection.setRequestProperty("Accept-Encoding", ""); int responseCode = connection.getResponseCode(); connection.disconnect(); return responseCode == HttpURLConnection.HTTP_OK; } catch (IOException e) { Log.e(TAG, "httpHeaderRequest: " + e.getClass() + ": " + e.getLocalizedMessage()); } finally { if (connection != null) { connection.disconnect(); } } return false; }
/** * @param file - the name of the file, as saved to the repo (including extension) * @return - the direct link */ public static String getStaticCreeperhostLink(String file) { String resolved = "http://repo.creeperhost.net/static/FTB2/" + file; HttpURLConnection connection = null; try { connection = (HttpURLConnection) new URL(resolved).openConnection(); } catch (MalformedURLException e1) { Logger.logError(e1.getMessage(), e1); } catch (IOException e1) { Logger.logError(e1.getMessage(), e1); } try { int retries = 1; while (connection.getResponseCode() != 200 && retries <= 3) { connection.disconnect(); resolved = "http://repo" + retries + ".creeperhost.net/static/FTB2/" + file; retries++; try { connection = (HttpURLConnection) new URL(resolved).openConnection(); } catch (MalformedURLException e) { Logger.logError(e.getMessage(), e); } catch (IOException e) { Logger.logError(e.getMessage(), e); } } } catch (IOException e) { Logger.logError(e.getMessage(), e); } connection.disconnect(); Logger.logInfo(resolved); return resolved; }
/* * sendRequest * Input: URL * Action: Send a HTTP GET request for that URL and get the response * Returns: The response */ private String sendRequest(String requestUrl) throws Exception { URL url = new URL(requestUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String responseCode = Integer.toString(connection.getResponseCode()); if (responseCode.startsWith("2")) { String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); connection.disconnect(); return response.toString(); } else { System.out.println( "Unable to connect to " + requestUrl + ". Please check whether the instance is up and also the security group settings"); connection.disconnect(); return null; } }
@Test @RunAsClient @Ignore public void testUpdateAssetFromJaxB(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL, "rest/packages/restPackage1/assets/model1"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty( "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_XML); connection.connect(); assertEquals(200, connection.getResponseCode()); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); JAXBContext context = JAXBContext.newInstance(Asset.class); Unmarshaller un = context.createUnmarshaller(); Asset a = (Asset) un.unmarshal(br); a.setDescription("An updated description."); a.setPublished(new Date(System.currentTimeMillis())); connection.disconnect(); HttpURLConnection conn2 = (HttpURLConnection) url.openConnection(); connection.setRequestProperty( "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); Marshaller ma = context.createMarshaller(); conn2.setRequestMethod("PUT"); conn2.setRequestProperty("Content-Type", MediaType.APPLICATION_XML); conn2.setRequestProperty("Content-Length", Integer.toString(a.toString().getBytes().length)); conn2.setUseCaches(false); conn2.setDoInput(true); conn2.setDoOutput(true); ma.marshal(a, conn2.getOutputStream()); assertEquals(200, connection.getResponseCode()); conn2.disconnect(); }
private Bitmap downloadBitmap(String url) { HttpURLConnection urlConnection = null; try { URL uri = new URL(url); urlConnection = (HttpURLConnection) uri.openConnection(); int statusCode = urlConnection.getResponseCode(); if (statusCode != HttpStatus.SC_OK) { return null; } InputStream inputStream = urlConnection.getInputStream(); if (inputStream != null) { Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } } catch (Exception e) { urlConnection.disconnect(); Log.w("ImageDownloader", "Error downloading image from " + url); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } return null; }
@Override protected String doInBackground(String... urls) { String startingUrl = urls[0]; URL url = null; try { url = new URL(startingUrl); } catch (MalformedURLException e) { // Return the starting URL if it is non-null, since that could still potentially be // a "valid" URL (e.g. one with a custom scheme). return (startingUrl != null) ? startingUrl : ""; } // Find the final target URL, manually following redirects if necessary. We can't use // HttpClient for this since the target may not be a supported URL (e.g. a market URL). int statusCode = -1; HttpURLConnection connection = null; String nextLocation = url.toString(); // Keep track of where we've been to detect redirect cycles. Set<String> redirectLocations = new HashSet<String>(); redirectLocations.add(nextLocation); try { do { connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", mUserAgent); connection.setInstanceFollowRedirects(false); statusCode = connection.getResponseCode(); if (statusCode == HttpStatus.SC_OK) { // Successfully reached the end of redirects: nextLocation is our target. connection.disconnect(); break; } else { // Depending on statusCode, we'll either continue to redirect, or error // out (in which case nextLocation will probably be null). nextLocation = connection.getHeaderField("location"); connection.disconnect(); // Check for redirect cycle. if (!redirectLocations.add(nextLocation)) { Log.d("MoPub", "Click redirect cycle detected -- will show blank."); return ""; } url = new URL(nextLocation); } } while (isStatusCodeForRedirection(statusCode)); } catch (IOException e) { // Return the last URL we tried to reach, since that could still potentially be a // "valid" URL (e.g. one with a custom scheme). return (nextLocation != null) ? nextLocation : ""; } finally { if (connection != null) connection.disconnect(); } return nextLocation; }
private void sendHttpMessage() { try { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); byte[] postData = new byte[0]; if (message != null) { postData = message.getBytes("UTF-8"); } connection.setRequestMethod(method); connection.setUseCaches(false); connection.setDoInput(true); connection.setConnectTimeout(HTTP_TIMEOUT_MS); connection.setReadTimeout(HTTP_TIMEOUT_MS); // TODO(glaznev) - query request origin from pref_room_server_url_key preferences. connection.addRequestProperty("origin", HTTP_ORIGIN); boolean doOutput = false; if (method.equals("POST")) { doOutput = true; connection.setDoOutput(true); connection.setFixedLengthStreamingMode(postData.length); } if (contentType == null) { connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); } else { connection.setRequestProperty("Content-Type", contentType); } // Send POST request. if (doOutput && postData.length > 0) { OutputStream outStream = connection.getOutputStream(); outStream.write(postData); outStream.close(); } // Get response.//得到应答 int responseCode = connection.getResponseCode(); if (responseCode != 200) { events.onHttpError( "Non-200 response to " + method + " to URL: " + url + " : " + connection.getHeaderField(null)); connection.disconnect(); return; } InputStream responseStream = connection.getInputStream(); String response = drainStream(responseStream); responseStream.close(); connection.disconnect(); events.onHttpComplete(response); } catch (SocketTimeoutException e) { events.onHttpError("HTTP " + method + " to " + url + " 超时"); } catch (IOException e) { events.onHttpError("HTTP " + method + " to " + url + " 错误: " + e.getMessage()); } }
public static Map<String, String> action( String action, String service, String url, Map<String, String> para) { try { StringBuffer req = new StringBuffer(); req.append( "<?xml version=\"1.0\"?>\r\n" + "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" " + "SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" + "<SOAP-ENV:Body><m:" + action + " xmlns:m=\"" + service + "\">"); if (para != null && para.size() > 0) { Set<Map.Entry<String, String>> entrySet = para.entrySet(); for (Map.Entry<String, String> entry : entrySet) { String key = entry.getKey(); req.append("<" + key + ">" + entry.getValue() + "</" + key + ">"); } } req.append("</m:" + action + "></SOAP-ENV:Body></SOAP-ENV:Envelope>"); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("SOAPAction", service + "#" + action); conn.setRequestProperty("Content-Type", "text/xml"); conn.setRequestProperty("Connection", "Close"); conn.setDoOutput(true); byte[] bs = req.toString().getBytes(); conn.setRequestProperty("Content-Length", String.valueOf(bs.length)); conn.getOutputStream().write(bs); Map<String, String> result = new HashMap<String, String>(); XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(new ResultHandler(result)); if (conn.getResponseCode() == 500) { conn.disconnect(); return null; } else { parser.parse(new InputSource(conn.getInputStream())); conn.disconnect(); return result; } } catch (Exception e) { } return null; }
private static HTTPRequestBundle getRequest( String address, IHttpRequestToAsyncTaskCommunication listener) { Log.i("WishUrlAddress", address); HttpURLConnection connection = null; String response = null; byte[] rawResponse = null; address = address.replace(" ", "%20"); int responseCode = 0; try { connection = getConnection(address); connection.setRequestMethod("GET"); connection = setConnectionHeader(connection); connection.connect(); responseCode = connection.getResponseCode(); int fileSize = connection.getContentLength(); InputStream in = getConnectionInputStream(connection); ByteArrayOutputStream byteArray = readInpdutStream(in, fileSize, listener); System.out.println( "Content Size: " + String.valueOf(fileSize) + " byteArray Size: " + String.valueOf(byteArray.size())); try { response = byteArray.toString(); // ("ISO-8859-2"); } catch (Exception e) { response = "ConvertToStringProblem"; } connection.disconnect(); connection = null; } catch (IOException e) { response = e.getMessage(); } finally { if (connection != null) { connection.disconnect(); connection = null; } } HTTPRequestBundle bundle = new HTTPRequestBundle(); bundle.setResponse(response); bundle.setRawResponse(rawResponse); bundle.setStatusCode(responseCode); return bundle; }
@Test public void shouldPostNodeToValidPathWithMixinTypes() throws Exception { URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/withMixinType"); HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON); String payload = "{ \"properties\": {\"jcr:mixinTypes\": \"mix:referenceable\"}}"; connection.getOutputStream().write(payload.getBytes()); JSONObject body = new JSONObject(getResponseFor(connection)); assertThat(body.length(), is(1)); JSONObject properties = body.getJSONObject("properties"); assertThat(properties, is(notNullValue())); assertThat(properties.length(), is(3)); assertThat(properties.getString("jcr:primaryType"), is("nt:unstructured")); assertThat(properties.getString("jcr:uuid"), is(notNullValue())); JSONArray values = properties.getJSONArray("jcr:mixinTypes"); assertThat(values, is(notNullValue())); assertThat(values.length(), is(1)); assertThat(values.getString(0), is("mix:referenceable")); assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_CREATED)); connection.disconnect(); postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/withMixinType"); connection = (HttpURLConnection) postUrl.openConnection(); // Make sure that we can retrieve the node with a GET connection.setDoOutput(true); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON); body = new JSONObject(getResponseFor(connection)); assertThat(body.length(), is(1)); properties = body.getJSONObject("properties"); assertThat(properties, is(notNullValue())); assertThat(properties.length(), is(3)); assertThat(properties.getString("jcr:primaryType"), is("nt:unstructured")); assertThat(properties.getString("jcr:uuid"), is(notNullValue())); values = properties.getJSONArray("jcr:mixinTypes"); assertThat(values, is(notNullValue())); assertThat(values.length(), is(1)); assertThat(values.getString(0), is("mix:referenceable")); assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_OK)); connection.disconnect(); }
/** A method to download json data from url */ protected String downloadUrl(String strUrl, boolean isDestinationRequest) throws IOException { String data = ""; InputStream iStream = null; HttpURLConnection urlConnection = null; Log.i("parse", "dans download URL n = " + n); Log.i("parse", "url = " + strUrl); try { URL url = new URL(strUrl); // Creating an http connection to communicate with url urlConnection = (HttpURLConnection) url.openConnection(); // Connecting to url urlConnection.connect(); // Reading data from url iStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); StringBuffer sb = new StringBuffer(); String line = ""; while ((line = br.readLine()) != null) { sb.append(line); } data = sb.toString(); br.close(); } catch (Exception e) { if (isDestinationRequest) Log.e("parse", "IOException download task destination"); else Log.e("parse", "IOException download task elevation n = " + n); data = "1"; try { iStream.close(); urlConnection.disconnect(); } catch (NullPointerException npe) { Log.i("parse", "null pointer exception iStream or urlConnection"); } Log.i("parse", "recomputing"); pause(TIME_BETWEEN_REQUEST); return downloadUrl(strUrl, isDestinationRequest); } Log.i("parse", "success"); iStream.close(); urlConnection.disconnect(); return data; }
@Override public void downloadWorkout(File dst, String key) throws Exception { HttpURLConnection conn = null; Exception ex = null; FileOutputStream out = null; try { conn = (HttpURLConnection) new URL(GET_WORKOUT_URL + key).openConnection(); conn.setRequestMethod("GET"); addCookies(conn); conn.connect(); getCookies(conn); InputStream in = new BufferedInputStream(conn.getInputStream()); out = new FileOutputStream(dst); int cnt = 0; byte buf[] = new byte[1024]; while (in.read(buf) > 0) { cnt += buf.length; out.write(buf); } System.err.println("downloaded workout key: " + key + " " + cnt + " bytes from " + getName()); in.close(); out.close(); conn.disconnect(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); if (responseCode == 200) { return; } ex = new Exception(amsg); } catch (Exception e) { ex = e; } if (conn != null) { try { conn.disconnect(); } catch (Exception e) { } } if (out != null) { try { out.close(); } catch (Exception e) { } } ex.printStackTrace(); throw ex; }
public static void main(String[] args) throws IOException, JSONException { // Ici, renseignez l'email dont vous voulez obtenir les valeurs des champs, et l'id du message String unicity = "*****@*****.**"; String idMessage = "000ABC"; // Lancement de la connexion pour remplir la requete String url = "http://v8.mailperformance.com/targets?unicity=" + unicity; HttpURLConnection con = openConn(url); con.setRequestMethod("GET"); // Verification des reponses int responseCode = con.getResponseCode(); if (responseCode != 200) { // Affichage de l'erreur System.out.print("Error : " + responseCode + ' ' + con.getResponseMessage()); } else { // Lecture des donnees ligne par lignes BufferedReader buffRead = new BufferedReader(new InputStreamReader(con.getInputStream())); String reply = buffRead.readLine(); con.disconnect(); buffRead.close(); // On recupere l'id de la cible JSONObject jObject = new JSONObject(reply); String idTarget = jObject.getString("id"); // Nouvelle url en fonction de l'id du message et de la cible url = "http://v8.mailperformance.com/actions/" + idMessage + "/targets/" + idTarget; // Lancement de la connexion pour remplir la requete con = openConn(url); con.setRequestProperty("Content-Length", ""); con.setRequestMethod("POST"); con.setDoOutput(true); // Envoie des informations dans la connection con.getOutputStream(); // Verification des reponses responseCode = con.getResponseCode(); if (responseCode != 204) { // Affichage de l'erreur System.out.print("Error : " + responseCode + ' ' + con.getResponseMessage()); } else { System.out.print("Message sent to " + unicity); } } con.disconnect(); }
@Override protected String doInBackground(String... params) { BufferedReader bufferedReader = null; HttpURLConnection urlConnection = null; StringBuffer buffer = new StringBuffer(); String line = null; try { URL url = new URL(params[0]); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); if (inputStream == null) { buffer = null; } InputStreamReader reader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(reader); while ((line = bufferedReader.readLine()) != null) { buffer.append(line); buffer.append("\n"); } } catch (IOException e) { if (urlConnection != null) { urlConnection.disconnect(); } e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } return buffer.toString(); }
public void download(String address) { StringBuilder jsonHtml = new StringBuilder(); try { // ���� url ���� URL url = new URL(address); // ���ؼ� ��ü �� HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDefaultUseCaches(false); conn.setDoInput(true); // �������� �б� ��� ���� conn.setDoOutput(false); // ������ ���� ��� ���� conn.setRequestMethod("POST"); // ��� ����� POST // ����Ǿ�� if (conn != null) { conn.setConnectTimeout(10000); conn.setUseCaches(false); // ����Ȯ�� �ڵ尡 ���ϵǾ��� �� if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); for (; ; ) { String line = br.readLine(); if (line == null) break; jsonHtml.append(line); } br.close(); } conn.disconnect(); } } catch (Exception e) { Log.w(TAG, e.getMessage()); } }
private Bitmap getBitmap(String url) { File f = fileCache.getFile(url); // from SD cache Bitmap b = decodeFile(f); if (b != null) return b; // from web try { Bitmap bitmap = null; URL imageUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setInstanceFollowRedirects(true); InputStream is = conn.getInputStream(); OutputStream os = new FileOutputStream(f); Utils.CopyStream(is, os); os.close(); conn.disconnect(); bitmap = decodeFile(f); return bitmap; } catch (Throwable ex) { ex.printStackTrace(); if (ex instanceof OutOfMemoryError) memoryCache.clear(); return null; } }
public String readUrl(String mapsApiDirectionsUrl) throws IOException { String data = ""; InputStream iStream = null; HttpURLConnection urlConnection = null; try { URL url = new URL(mapsApiDirectionsUrl); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.connect(); iStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); StringBuffer sb = new StringBuffer(); String line = ""; while ((line = br.readLine()) != null) { sb.append(line); } data = sb.toString(); br.close(); } catch (Exception e) { Log.d("Exception while reading url", e.toString()); } finally { iStream.close(); urlConnection.disconnect(); } return data; }
public boolean loginToRouter(String name, String pass) { routerLines = new ArrayList<String>(); Log.w("LOGINTOROUTER", String.valueOf((!breaker && !logged))); if (!breaker && !logged) { try { HttpURLConnection c = (HttpURLConnection) new URL("http://192.168.1.1").openConnection(); Log.w("LOGINTOROUTER", name + pass); c.setRequestProperty("Authorization", getB64Auth(name, pass)); if (c.getResponseMessage().equals("Unauthorized")) { c.disconnect(); Log.w("LOGINTOROUTER", "Fail?"); } else { breaker = true; logged = true; Log.w("myApp", c.getResponseMessage()); Log.w("myApp", "presla kvazi autentizacia"); InputStream is = c.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String line; while ((line = in.readLine()) != null) { routerLines.add(line); } } } catch (IOException e) { e.printStackTrace(); } } return breaker; }
public static String visitWeb(String urlStr) { URL url = null; HttpURLConnection httpConn = null; InputStream in = null; try { url = new URL(urlStr); httpConn = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.setRequestProperty("User-Agent", "Mozilla/4.0(compatible;MSIE 6.0;Windows 2000)"); in = httpConn.getInputStream(); return convertStreamToString(in); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); httpConn.disconnect(); } catch (Exception ex) { ex.printStackTrace(); } } return null; }