List of usage examples for java.net HttpURLConnection setDoInput
public void setDoInput(boolean doinput)
From source file:eu.codeplumbers.cosi.services.CosiLoyaltyCardService.java
/** * Make remote request to get all loyalty cards stored in Cozy *///from w w w.ja v a2s. c o m public String getRemoteLoyaltyCards() { URL urlO = null; try { urlO = new URL(designUrl); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoInput(true); conn.setRequestMethod("POST"); // read the response int status = conn.getResponseCode(); InputStream in = null; if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { in = conn.getErrorStream(); } else { in = conn.getInputStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONArray jsonArray = new JSONArray(result); if (jsonArray != null) { if (jsonArray.length() == 0) { EventBus.getDefault() .post(new LoyaltyCardSyncEvent(SYNC_MESSAGE, "Your Cozy has no calls stored.")); LoyaltyCard.setAllUnsynced(); } else { for (int i = 0; i < jsonArray.length(); i++) { try { EventBus.getDefault().post(new LoyaltyCardSyncEvent(SYNC_MESSAGE, "Reading loyalty cards on Cozy " + i + "/" + jsonArray.length() + "...")); JSONObject loyaltyCardJson = jsonArray.getJSONObject(i).getJSONObject("value"); LoyaltyCard loyaltyCard = LoyaltyCard .getByRemoteId(loyaltyCardJson.get("_id").toString()); if (loyaltyCard == null) { loyaltyCard = new LoyaltyCard(loyaltyCardJson); } else { loyaltyCard.setRemoteId(loyaltyCardJson.getString("_id")); loyaltyCard.setRawValue(loyaltyCardJson.getString("rawValue")); loyaltyCard.setCode(loyaltyCardJson.getInt("code")); loyaltyCard.setLabel(loyaltyCardJson.getString("label")); loyaltyCard.setCreationDate(loyaltyCardJson.getString("creationDate")); } loyaltyCard.save(); } catch (JSONException e) { EventBus.getDefault() .post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } } } } else { errorMessage = new JSONObject(result).getString("error"); EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, errorMessage)); stopSelf(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } return errorMessage; }
From source file:org.jongo.mocks.JongoClient.java
private JongoResponse doRequest(final String url, final String method, final String jsonParameters) { JongoResponse response = null;// w w w . j a va 2 s . c o m try { HttpURLConnection con = (HttpURLConnection) new URL(jongoUrl + url).openConnection(); con.setRequestMethod(method); con.setRequestProperty("Accept", MediaType.APPLICATION_XML); con.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON); con.setRequestProperty("Content-Length", "" + Integer.toString(jsonParameters.getBytes().length)); con.setDoOutput(true); con.setDoInput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(jsonParameters); wr.flush(); wr.close(); // BufferedReader r = new BufferedReader(new InputStreamReader(con.getInputStream())); BufferedReader r = null; if (con.getResponseCode() != Response.Status.OK.getStatusCode() && con.getResponseCode() != Response.Status.CREATED.getStatusCode()) { r = new BufferedReader(new InputStreamReader(con.getErrorStream())); } else { r = new BufferedReader(new InputStreamReader(con.getInputStream())); } StringBuilder rawresponse = new StringBuilder(); String strLine = null; while ((strLine = r.readLine()) != null) { rawresponse.append(strLine); rawresponse.append("\n"); } try { response = XmlXstreamTest.successFromXML(rawresponse.toString()); } catch (Exception e) { response = XmlXstreamTest.errorFromXML(rawresponse.toString()); } } catch (Exception ex) { ex.printStackTrace(); } return response; }
From source file:com.googlecode.jmxtrans.model.output.LibratoWriter.java
private void writeToLibrato(Server server, Query query, List<Result> results) { HttpURLConnection urlConnection = null; try {//www. j a v a 2 s .co m if (proxy == null) { urlConnection = (HttpURLConnection) url.openConnection(); } else { urlConnection = (HttpURLConnection) url.openConnection(proxy); } urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setReadTimeout(libratoApiTimeoutInMillis); urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8"); urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthentication); urlConnection.setRequestProperty("User-Agent", httpUserAgent); serialize(server, query, results, urlConnection.getOutputStream()); int responseCode = urlConnection.getResponseCode(); if (responseCode != 200) { logger.warn("Failure {}:'{}' to send result to Librato server '{}' with proxy {}, username {}", responseCode, urlConnection.getResponseMessage(), url, proxy, username); } if (logger.isTraceEnabled()) { StringWriter out = new StringWriter(); IOUtils.copy(urlConnection.getInputStream(), out); logger.trace(out.toString()); } } catch (Exception e) { logger.warn("Failure to send result to Librato server '{}' with proxy {}, username {}", url, proxy, username, e); } finally { if (urlConnection != null) { try { InputStream in = urlConnection.getInputStream(); IOUtils.copy(in, NullOutputStream.NULL_OUTPUT_STREAM); IOUtils.closeQuietly(in); InputStream err = urlConnection.getErrorStream(); if (err != null) { IOUtils.copy(err, NullOutputStream.NULL_OUTPUT_STREAM); IOUtils.closeQuietly(err); } } catch (IOException e) { logger.warn("Exception flushing http connection", e); } } } }
From source file:com.hybris.mobile.data.WebServiceDataProvider.java
/** * Synchronous call to the OCC web services * //from w ww.j a v a 2 s . c o m * @param url * The url * @param isAuthorizedRequest * Whether this request requires the authorization token sending * @param httpMethod * method type (GET, PUT, POST, DELETE) * @param httpBody * Data to be sent in the body (Can be empty) * @return The data from the server as a string, in almost all cases JSON * @throws MalformedURLException * @throws IOException * @throws ProtocolException */ public static String getResponse(Context context, String url, Boolean isAuthorizedRequest, String httpMethod, Bundle httpBody) throws MalformedURLException, IOException, ProtocolException, JSONException { // Refresh if necessary if (isAuthorizedRequest && WebServiceAuthProvider.tokenExpiredHint(context)) { WebServiceAuthProvider.refreshAccessToken(context); } boolean refreshLimitReached = false; int refreshed = 0; String response = ""; while (!refreshLimitReached) { // If we have refreshed max number of times, we will not do so again if (refreshed == 1) { refreshLimitReached = true; } // Make the connection and get the response OutputStream os; HttpURLConnection connection; if (httpMethod.equals("GET") && httpBody != null && !httpBody.isEmpty()) { url = url + "?" + encodePostBody(httpBody); } URL requestURL = new URL(addParameters(context, url)); if (StringUtils.equalsIgnoreCase(requestURL.getProtocol(), "https")) { trustAllHosts(); HttpsURLConnection https = createSecureConnection(requestURL); https.setHostnameVerifier(DO_NOT_VERIFY); if (isAuthorizedRequest) { String authValue = "Bearer " + SDKSettings.getSharedPreferenceString(context, "access_token"); https.setRequestProperty("Authorization", authValue); } connection = https; } else { connection = createConnection(requestURL); } connection.setRequestMethod(httpMethod); if (!httpMethod.equals("GET") && !httpMethod.equals("DELETE")) { connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); if (httpBody != null && !httpBody.isEmpty()) { os = new BufferedOutputStream(connection.getOutputStream()); os.write(encodePostBody(httpBody).getBytes()); os.flush(); } } response = ""; try { LoggingUtils.d(LOG_TAG, connection.toString()); response = readFromStream(connection.getInputStream()); } catch (FileNotFoundException e) { LoggingUtils.e(LOG_TAG, "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(), context); response = readFromStream(connection.getErrorStream()); } finally { connection.disconnect(); } // Allow for calls to return nothing if (response.length() == 0) { return ""; } // Check for JSON parsing errors (will throw JSONException is can't be parsed) JSONObject object = new JSONObject(response); // If no error, return response if (!object.has("error")) { return response; } // If there is a refresh token error, refresh the token else if (object.getString("error").equals("invalid_token")) { if (refreshLimitReached) { // Give up return response; } else { // Refresh the token WebServiceAuthProvider.refreshAccessToken(context); refreshed++; } } } // while(!refreshLimitReached) // There is an error other than a refresh error, so return the response return response; }
From source file:com.workfront.api.StreamClient.java
private HttpURLConnection createConnection(String spec, String method) throws IOException { URL url = new URL(spec); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (conn instanceof HttpsURLConnection) { ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER); }//from w w w. j a v a 2 s .com conn.setAllowUserInteraction(false); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setConnectTimeout(60000); conn.setReadTimeout(300000); return conn; }
From source file:com.googlecode.jsonrpc4j.JsonRpcHttpClient.java
/** * Prepares a connection to the server./*from w ww . jav a 2 s. c o m*/ * @param extraHeaders extra headers to add to the request * @return the unopened connection * @throws IOException */ protected HttpURLConnection prepareConnection(Map<String, String> extraHeaders) throws IOException { // create URLConnection HttpURLConnection con = (HttpURLConnection) serviceUrl.openConnection(connectionProxy); con.setConnectTimeout(connectionTimeoutMillis); con.setReadTimeout(readTimeoutMillis); con.setAllowUserInteraction(false); con.setDefaultUseCaches(false); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setInstanceFollowRedirects(true); con.setRequestMethod("POST"); // do stuff for ssl if (HttpsURLConnection.class.isInstance(con)) { HttpsURLConnection https = HttpsURLConnection.class.cast(con); if (hostNameVerifier != null) { https.setHostnameVerifier(hostNameVerifier); } if (sslContext != null) { https.setSSLSocketFactory(sslContext.getSocketFactory()); } } // add headers con.setRequestProperty("Content-Type", "application/json-rpc"); for (Entry<String, String> entry : headers.entrySet()) { con.setRequestProperty(entry.getKey(), entry.getValue()); } for (Entry<String, String> entry : extraHeaders.entrySet()) { con.setRequestProperty(entry.getKey(), entry.getValue()); } // return it return con; }
From source file:io.mapzone.arena.refine.OrgPersonSplitTableRefineFunction.java
protected Point coordinateForOrganisation(final String organisation, final String plz, final String strasseHausNr) throws Exception { if (StringUtils.isBlank(plz) || StringUtils.isBlank(strasseHausNr)) { return null; }/*from ww w . ja v a2 s . c o m*/ final String search1 = "\"lat\":"; final String search2 = ",\"lng\":"; final String search3 = "}"; final String key = "AAdiimU0EwFAoY3G7M7hFx694EdRTuSa"; final String location = URLEncoder.encode(Joiner.on(", ").join(plz, strasseHausNr), "UTF-8"); if (locations.containsKey(location)) { String coord = locations.getProperty(location); String[] coords = coord.split("\\|"); return GEOMETRYFACTORY .createPoint(new Coordinate(Double.parseDouble(coords[0]), Double.parseDouble(coords[1]))); } else { final String url = String.format( "http://www.mapquestapi.com/geocoding/v1/address?key=%1$2s&location=%2$2s", key, location); final HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("GET"); con.addRequestProperty("Accept", "application/json"); con.setDoInput(true); con.setDoOutput(true); try { if (con.getResponseCode() != 200) { System.err.println("Keine Koordinate fr " + organisation + ": " + con.getResponseMessage()); } else { final String out = IOUtils.toString(con.getInputStream()); int index1 = out.indexOf(search1); if (index1 > 0) { String out2 = out.substring(index1 + search1.length()); int index3 = out2.indexOf(search3); if (index3 > 0) { out2 = out2.substring(0, index3); int index2 = out2.indexOf(search2); if (index2 > 0) { final String latitude = out2.substring(0, index2); final String longitude = out2.substring(index2 + search2.length()); Point point = (latitude != null && longitude != null) ? GEOMETRYFACTORY.createPoint( new Coordinate(Double.parseDouble(longitude), Double.parseDouble(latitude))) : null; return point; } } } } } finally { con.disconnect(); } } return null; }
From source file:org.jongo.mocks.JongoClient.java
private JongoResponse doRequest(final String url, final List<NameValuePair> parameters) { final String urlParameters = URLEncodedUtils.format(parameters, "UTF-8"); JongoResponse response = null;//from w w w. j a v a 2 s . co m try { HttpURLConnection con = (HttpURLConnection) new URL(jongoUrl + url).openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept", MediaType.APPLICATION_XML); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); con.setDoOutput(true); con.setDoInput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); BufferedReader r = null; if (con.getResponseCode() != Response.Status.CREATED.getStatusCode()) { r = new BufferedReader(new InputStreamReader(con.getErrorStream())); } else { r = new BufferedReader(new InputStreamReader(con.getInputStream())); } StringBuilder rawresponse = new StringBuilder(); String strLine = null; while ((strLine = r.readLine()) != null) { rawresponse.append(strLine); rawresponse.append("\n"); } try { response = XmlXstreamTest.successFromXML(rawresponse.toString()); } catch (Exception e) { response = XmlXstreamTest.errorFromXML(rawresponse.toString()); } } catch (Exception ex) { ex.printStackTrace(); } return response; }
From source file:org.jmxtrans.embedded.output.StackdriverWriter.java
/** * Send given metrics to the Stackdriver server using HTTP * /* w w w.j a v a 2 s. co m*/ * @param results * Iterable collection of data points */ @Override public void write(Iterable<QueryResult> results) { logger.debug("Export to '{}', proxy {} metrics {}", url, proxy, results); HttpURLConnection urlConnection = null; try { if (proxy == null) { urlConnection = (HttpURLConnection) url.openConnection(); } else { urlConnection = (HttpURLConnection) url.openConnection(proxy); } urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setReadTimeout(stackdriverApiTimeoutInMillis); urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8"); urlConnection.setRequestProperty("x-stackdriver-apikey", apiKey); serialize(results, urlConnection.getOutputStream()); int responseCode = urlConnection.getResponseCode(); if (responseCode != 200 && responseCode != 201) { exceptionCounter.incrementAndGet(); logger.warn("Failure {}:'{}' to send result to Stackdriver server '{}' with proxy {}", responseCode, urlConnection.getResponseMessage(), url, proxy); } if (logger.isTraceEnabled()) { IoUtils2.copy(urlConnection.getInputStream(), System.out); } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Failure to send result to Stackdriver server '{}' with proxy {}", url, proxy, e); } finally { if (urlConnection != null) { try { InputStream in = urlConnection.getInputStream(); IoUtils2.copy(in, IoUtils2.nullOutputStream()); IoUtils2.closeQuietly(in); InputStream err = urlConnection.getErrorStream(); if (err != null) { IoUtils2.copy(err, IoUtils2.nullOutputStream()); IoUtils2.closeQuietly(err); } urlConnection.disconnect(); } catch (IOException e) { logger.warn("Error flushing http connection for one result, continuing"); logger.debug("Stack trace for the http connection, usually a network timeout", e); } } } }
From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java
protected Response invoke(UrlBuilder url, String method, String contentType, Map<String, String> headers, Output writer, BindingSession session, BigInteger offset, BigInteger length) { try {/*ww w. jav a2 s .c o m*/ // log before connect //Log.d("URL", url.toString()); if (LOG.isDebugEnabled()) { LOG.debug(method + " " + url); } // connect HttpURLConnection conn = getHttpURLConnection(new URL(url.toString())); conn.setRequestMethod(method); conn.setDoInput(true); conn.setDoOutput(writer != null); conn.setAllowUserInteraction(false); conn.setUseCaches(false); conn.setRequestProperty(HTTP.USER_AGENT, ClientVersion.OPENCMIS_CLIENT); // timeouts int connectTimeout = session.get(SessionParameter.CONNECT_TIMEOUT, -1); if (connectTimeout >= 0) { conn.setConnectTimeout(connectTimeout); } int readTimeout = session.get(SessionParameter.READ_TIMEOUT, -1); if (readTimeout >= 0) { conn.setReadTimeout(readTimeout); } // set content type if (contentType != null) { conn.setRequestProperty(HTTP.CONTENT_TYPE, contentType); } // set other headers if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { conn.addRequestProperty(header.getKey(), header.getValue()); } } // authenticate AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session); if (authProvider != null) { Map<String, List<String>> httpHeaders = authProvider.getHTTPHeaders(url.toString()); if (httpHeaders != null) { for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) { if (header.getValue() != null) { for (String value : header.getValue()) { conn.addRequestProperty(header.getKey(), value); } } } } if (conn instanceof HttpsURLConnection) { SSLSocketFactory sf = authProvider.getSSLSocketFactory(); if (sf != null) { ((HttpsURLConnection) conn).setSSLSocketFactory(sf); } HostnameVerifier hv = authProvider.getHostnameVerifier(); if (hv != null) { ((HttpsURLConnection) conn).setHostnameVerifier(hv); } } } // range if ((offset != null) || (length != null)) { StringBuilder sb = new StringBuilder("bytes="); if ((offset == null) || (offset.signum() == -1)) { offset = BigInteger.ZERO; } sb.append(offset.toString()); sb.append("-"); if ((length != null) && (length.signum() == 1)) { sb.append(offset.add(length.subtract(BigInteger.ONE)).toString()); } conn.setRequestProperty("Range", sb.toString()); } // compression Object compression = session.get(AlfrescoSession.HTTP_ACCEPT_ENCODING); if (compression == null) { conn.setRequestProperty("Accept-Encoding", ""); } else { Boolean compressionValue; try { compressionValue = Boolean.parseBoolean(compression.toString()); if (compressionValue) { conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); } else { conn.setRequestProperty("Accept-Encoding", ""); } } catch (Exception e) { conn.setRequestProperty("Accept-Encoding", compression.toString()); } } // locale if (session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) instanceof String && session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) != null) { conn.setRequestProperty("Accept-Language", session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE).toString()); } // send data if (writer != null) { Object chunkTransfert = session.get(AlfrescoSession.HTTP_CHUNK_TRANSFERT); if (chunkTransfert != null && Boolean.parseBoolean(chunkTransfert.toString())) { conn.setRequestProperty(HTTP.TRANSFER_ENCODING, "chunked"); conn.setChunkedStreamingMode(0); } conn.setConnectTimeout(900000); OutputStream connOut = null; Object clientCompression = session.get(SessionParameter.CLIENT_COMPRESSION); if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) { conn.setRequestProperty(HTTP.CONTENT_ENCODING, "gzip"); connOut = new GZIPOutputStream(conn.getOutputStream(), 4096); } else { connOut = conn.getOutputStream(); } OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE); writer.write(out); out.flush(); } // connect conn.connect(); // get stream, if present int respCode = conn.getResponseCode(); InputStream inputStream = null; if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED) || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION) || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) { inputStream = conn.getInputStream(); } // log after connect if (LOG.isTraceEnabled()) { LOG.trace(method + " " + url + " > Headers: " + conn.getHeaderFields()); } // forward response HTTP headers if (authProvider != null) { authProvider.putResponseHeaders(url.toString(), respCode, conn.getHeaderFields()); } // get the response return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream, conn.getErrorStream()); } catch (Exception e) { throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e); } }