List of usage examples for java.net HttpURLConnection setDoInput
public void setDoInput(boolean doinput)
From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java
private HttpURLConnection buildConnection(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout);//from www . j av a 2 s.c o m connection.setUseCaches(false); // Set the authorization header if one has been specified if (authorization != null) { connection.setRequestProperty("Authorization", authorization); } return connection; }
From source file:eu.codeplumbers.cosi.api.tasks.DeleteFileTask.java
private String deleteFileRequest(File file) { String result = ""; URL urlO = null;/* www. j a v a2 s. c o m*/ try { urlO = new URL(url + file.getRemoteId() + "/"); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoOutput(false); conn.setDoInput(true); conn.setRequestMethod("DELETE"); // read the response InputStream in = new BufferedInputStream(conn.getInputStream()); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); result = writer.toString(); in.close(); conn.disconnect(); } catch (MalformedURLException e) { result = e.getLocalizedMessage(); } catch (ProtocolException e) { result = e.getLocalizedMessage(); e.printStackTrace(); } catch (IOException e) { result = e.getLocalizedMessage(); } return result; }
From source file:com.pocketsoap.salesforce.soap.ChatterClient.java
private String postSuspectsComment(String postId, Map<String, String> suspects, boolean retryOnInvalidSession) throws MalformedURLException, IOException, XMLStreamException, FactoryConfigurationError { URL instanceUrl = new URL(session.instanceServerUrl); URL url = new URL(instanceUrl.getProtocol(), instanceUrl.getHost(), instanceUrl.getPort(), "/services/data/v24.0/chatter/feed-items/" + postId + "/comments"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); try {// w w w. j a v a 2 s . c o m conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Authorization", "OAuth " + session.sessionId); final Comment comment = new Comment(); final List<MessageSegment> messageSegments = comment.getBody().getMessageSegments(); messageSegments.add(new TextMessageSegment("Suspects: ")); Iterator<Entry<String, String>> it = suspects.entrySet().iterator(); while (it.hasNext()) { Entry<String, String> ids = it.next(); String sfdcId = ids.getValue(); if (sfdcId != null) { //Convert the login to an SFDC ID sfdcId = UserService.getUserId(session, sfdcId); } if (sfdcId == null) { //not mapped messageSegments.add(new TextMessageSegment(ids.getKey())); } else { messageSegments.add(new MentionMessageSegment(sfdcId)); } if (it.hasNext()) { messageSegments.add(new TextMessageSegment(", ")); } } final OutputStream bodyStream = conn.getOutputStream(); ObjectMapper mapper = new ObjectMapper(); MappingJsonFactory jsonFactory = new MappingJsonFactory(); JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(bodyStream); mapper.writeValue(jsonGenerator, comment); bodyStream.close(); conn.getInputStream().close(); //Don't care about the response } catch (IOException e) { if (retryOnInvalidSession && conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { SessionCache.get().revoke(credentials); return postSuspectsComment(postId, suspects, false); } BufferedReader r = new BufferedReader(new InputStreamReader(conn.getErrorStream())); String error = ""; String line; while ((line = r.readLine()) != null) { error += line + '\n'; } System.out.println(error); throw e; } return null; }
From source file:com.helpmobile.rest.RestAccess.java
public String doGetRequest(String request, Map<String, Object> data, String method) throws MalformedURLException, IOException { StringBuilder postData = new StringBuilder(); for (Map.Entry<String, Object> param : data.entrySet()) { if (postData.length() != 0) { postData.append('&'); }/*from w ww . j a v a 2s .co m*/ postData.append(URLEncoder.encode(param.getKey(), "UTF-8")); postData.append('='); postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8")); } URL path; path = new URL(ADDRESS + request + "?" + postData.toString()); HttpURLConnection conn = (HttpURLConnection) path.openConnection(); conn.setRequestMethod(method); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("AppKey", KEY); conn.setUseCaches(false); conn.setDoInput(true); conn.setRequestProperty("Content-Length", "0"); conn.setDoOutput(true); OutputStream output = conn.getOutputStream(); output.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); conn.disconnect(); //print result return response.toString(); }
From source file:eu.inmite.apps.smsjizdenka.service.UpdateService.java
private InputStream getIS(int addr, boolean online) throws IOException { if (!online || LOCAL_DEFINITION_TESTING) { if (addr == URL_VERSION_ID) { return getResources().getAssets().open(URL_VERSION); } else if (addr == URL_TICKETS_ID) { return getResources().getAssets().open(URL_TICKETS); } else {//from w ww. ja v a2 s . c o m throw new IOException("requested addr " + addr + " not found"); } } else { URL url; if (addr == URL_VERSION_ID) { url = new URL(Constants.DATA_URL_BASE + URL_VERSION); } else if (addr == URL_TICKETS_ID) { url = new URL(Constants.DATA_URL_BASE + URL_TICKETS); } else { throw new IOException("requested addr " + addr + " not found"); } try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(30000); connection.setRequestMethod("GET"); connection.setDoInput(true); connection.setDoOutput(false); if (connection.getResponseCode() != 200) { connection.disconnect(); throw new IOException("status " + connection.getResponseCode() + " received"); } if (addr == URL_VERSION_ID) { DebugLog.i("Downloading definition version info..."); } else if (addr == URL_TICKETS_ID) { DebugLog.i("Downloading new tickets definition..."); } return connection.getInputStream(); } catch (SecurityException e) { throw new IOException("Internet access denied"); } } }
From source file:com.aegiswallet.tasks.GetCurrencyInfoTask.java
@Override protected Void doInBackground(String... strings) { Log.d(TAG, "inside currency info task..."); if (fileExistance(Constants.BLOCKCHAIN_CURRENCY_FILE_NAME) && !shouldRefreshFile(Constants.BLOCKCHAIN_CURRENCY_FILE_NAME)) { return null; }//from www . ja v a 2 s. co m HttpURLConnection urlConnection = null; URL url = null; jsonObject = null; InputStream inStream = null; try { url = new URL(urlString.toString()); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.connect(); inStream = urlConnection.getInputStream(); BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream)); String temp, response = ""; while ((temp = bReader.readLine()) != null) { response += temp; } jsonObject = (JSONObject) new JSONTokener(response).nextValue(); } catch (Exception e) { } finally { if (inStream != null) { try { // this will close the bReader as well inStream.close(); } catch (IOException ignored) { Log.e("Currency Task", "File Close IO Exception: " + ignored.getMessage()); } } if (urlConnection != null) { urlConnection.disconnect(); } } if (jsonObject != null) { try { FileOutputStream fos = context.getApplicationContext() .openFileOutput(Constants.BLOCKCHAIN_CURRENCY_FILE_NAME, Context.MODE_PRIVATE); fos.write(jsonObject.toString().getBytes()); fos.close(); } catch (IOException e) { Log.e("Currency Task", "Cannot save or create file " + e.getMessage()); } } return null; }
From source file:com.helpmobile.rest.RestAccess.java
public String doPostRequest(String request, Map<String, Object> data, String method) throws MalformedURLException, IOException { StringBuilder postData = new StringBuilder(); for (Map.Entry<String, Object> param : data.entrySet()) { if (postData.length() != 0) { postData.append('&'); }/*from w ww .j ava 2 s . co m*/ postData.append(URLEncoder.encode(param.getKey(), "UTF-8")); postData.append('='); postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8")); } URL path; if (method.equalsIgnoreCase(METHOD_GET)) { path = new URL(ADDRESS + request + "?" + postData.toString()); } else { path = new URL(ADDRESS + request); } HttpURLConnection conn = (HttpURLConnection) path.openConnection(); conn.setRequestMethod(method); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("AppKey", KEY); conn.setUseCaches(false); conn.setDoInput(true); if (method.equalsIgnoreCase(METHOD_POST)) { byte[] result = postData.toString().getBytes("UTF-8"); conn.setRequestProperty("Content-Length", Integer.toString(result.length)); conn.setDoOutput(true); OutputStream output = conn.getOutputStream(); output.write(result); output.flush(); } BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); conn.disconnect(); //print result return response.toString(); }
From source file:org.esupportail.twitter.services.OAuthTwitterApplicationOnlyService.java
public void afterPropertiesSet() throws Exception { HttpURLConnection connection = null; String encodedCredentials = encodeKeys(oAuthTwitterConfig.getConsumerKey(), oAuthTwitterConfig.getConsumerSecret()); try {//from ww w . j ava 2 s. co m URL url = new URL(URL_TWITTER_OAUTH2_TOKEN); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Host", "api.twitter.com"); connection.setRequestProperty("User-Agent", ESUPTWITTER_USERAGENT); connection.setRequestProperty("Authorization", "Basic " + encodedCredentials); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); connection.setRequestProperty("Content-Length", "29"); connection.setUseCaches(false); writeRequest(connection, "grant_type=client_credentials"); String jsonResponse = readResponse(connection); log.debug("jsonResponse of the bearer oauth request : " + jsonResponse); if (connection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) { log.error( "HTTP 403 (Forbidden) returned from Twitter API call for bearer token. Check values of Consumer Key and Consumer Secret in tokens.properties"); throw new RejectedAuthorizationException("", "HTTP 403 (Forbidden) returned attempting to get Twitter API bearer token"); } // Parse the JSON response into a JSON mapped object to fetch fields from. JSONObject obj = new JSONObject(jsonResponse); if (obj != null) { applicationOnlyBearerToken = (String) obj.get("access_token"); } } catch (MalformedURLException e) { throw new IOException("Invalid endpoint URL specified.", e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.baseproject.volley.toolbox.HurlStack.java
/** * Opens an {@link HttpURLConnection} with parameters. * //from ww w. j a va 2s . c om * @param url * @return an open connection * @throws IOException */ private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException { HttpURLConnection connection = createConnection(url); // int timeoutMs = request.getTimeoutMs(); connection.setConnectTimeout(request.getConnTimeoutMs()); connection.setReadTimeout(request.getReadTimeoutMs()); connection.setUseCaches(false); connection.setDoInput(true); // use caller-provided custom SslSocketFactory, if any, for HTTPS if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) { ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory); } return connection; }
From source file:eu.codeplumbers.cosi.api.tasks.DeleteFileTask.java
@Override protected String doInBackground(File... files) { for (int i = 0; i < files.length; i++) { File file = files[i];/*ww w . ja v a 2 s .co m*/ String binaryRemoteId = file.getRemoteId(); if (!binaryRemoteId.isEmpty()) { publishProgress("Deleting file: " + file.getName(), "0", "100"); URL urlO = null; try { urlO = new URL(url + binaryRemoteId + "/binaries/file"); 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("DELETE"); InputStream in = null; // read the response int status = conn.getResponseCode(); 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(); if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { errorMessage = conn.getResponseMessage(); } else { errorMessage = deleteFileRequest(file); if (errorMessage == "") { java.io.File newFile = file.getLocalPath(); if (newFile.exists()) { newFile.delete(); } file.delete(); } else { return errorMessage; } } } catch (MalformedURLException e) { errorMessage = e.getLocalizedMessage(); } catch (ProtocolException e) { errorMessage = e.getLocalizedMessage(); } catch (IOException e) { errorMessage = e.getLocalizedMessage(); } } } return errorMessage; }