List of usage examples for java.net HttpURLConnection HTTP_OK
int HTTP_OK
To view the source code for java.net HttpURLConnection HTTP_OK.
Click Source Link
From source file:de.dekies.android.websms.connector.smsglobal.ConnectorSmsGlobal.java
/** * Send data./*from w ww .j ava2 s . co m*/ * * @param context * {@link Context} * @param command * {@link ConnectorCommand} */ private void sendData(final Context context, // . final ConnectorCommand command) { // do IO try { // get Connection final String text = command.getText(); final boolean checkOnly = (text == null || text.length() == 0); final StringBuilder url = new StringBuilder(); final ConnectorSpec cs = this.getSpec(context); final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context); if (checkOnly) { url.append(URL_BALANCE); } else { url.append(URL_SEND); } ArrayList<BasicNameValuePair> postData = // TODO: use interface // after api is adapted: // List<NameValuePair> new ArrayList<BasicNameValuePair>(); // mandatory arguments postData.add(new BasicNameValuePair("user", p.getString(Preferences.PREFS_USER, ""))); postData.add(new BasicNameValuePair("password", p.getString(Preferences.PREFS_PASSWORD, ""))); if (checkOnly) { // 2 digit ISO country code of SMS destination // ISO country codes can be found at // http://en.wikipedia.org/wiki/ISO_3166?1 the ISO code is a // 2?digit // alpha representation of the country. An example is, Australia // = AU, United Kingdom = GB postData.add(new BasicNameValuePair("country", "DE")); // TODO // determine // via // recipient // number } else { postData.add(new BasicNameValuePair("action", "sendsms")); final String customSender = command.getCustomSender(); if (customSender == null) { postData.add(new BasicNameValuePair("from", Utils.national2international(command.getDefPrefix(), Utils.getSender(context, command.getDefSender())))); } else { postData.add(new BasicNameValuePair("from", customSender)); } final long sendLater = command.getSendLater(); if (sendLater > 0) { postData.add(new BasicNameValuePair("scheduledatetime", DateFormat.format(DATEFORMAT, sendLater).toString())); } postData.add(new BasicNameValuePair("text", URLEncoder.encode(text, "ISO-8859-15"))); postData.add(new BasicNameValuePair("to", Utils.joinRecipientsNumbers(command.getRecipients(), ",", false))); // TODO: optional, handle messages > 160 signs // postData.add(new BasicNameValuePair("maxsplit", // "number of times allowed to split")); } // send data HttpResponse response = Utils.getHttpClient(url.toString(), null, postData, null, null, null, false); int resp = response.getStatusLine().getStatusCode(); if (resp != HttpURLConnection.HTTP_OK) { this.checkReturnCode(context, resp); throw new WebSMSException(context, R.string.error_http, " " + resp); } String htmlText = Utils.stream2str(response.getEntity().getContent()).trim(); String[] lines = htmlText.split("\n"); Log.d(TAG, "--HTTP RESPONSE--"); Log.d(TAG, htmlText); Log.d(TAG, "--HTTP RESPONSE--"); htmlText = null; for (String s : lines) { if (s.startsWith("CREDITS: ")) { cs.setBalance(s.split(" ")[1].trim() + "\u20AC"); // TODO // line // split } } } catch (IOException e) { Log.e(TAG, null, e); throw new WebSMSException(e.getMessage()); } }
From source file:com.nimbits.user.GoogleAuthentication.java
private String extractAuthTokenFromResponse(final HttpURLConnection urlConnection) throws IOException { int responseCode = urlConnection.getResponseCode(); final StringBuilder resp = new StringBuilder(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = urlConnection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream)); String line;//from w w w. java 2 s . c om while ((line = rd.readLine()) != null) { if (line.startsWith("Auth=")) { resp.append(line.substring(5)); } } rd.close(); } return resp.toString(); }
From source file:org.jboss.pull.player.LabelProcessor.java
private ModelNode getIssues() throws IOException { final ModelNode resultIssues = new ModelNode(); try {//from w ww . ja va2s . c o m // Get all the issues for the repository final HttpGet get = new HttpGet(GitHubApi.GITHUB_BASE_URL + "/issues"); GitHubApi.addDefaultHeaders(get); final HttpResponse response = execute(get, HttpURLConnection.HTTP_OK); ModelNode responseResult = ModelNode.fromJSONStream(response.getEntity().getContent()); for (ModelNode node : responseResult.asList()) { // We only want issues with a pull request if (node.hasDefined("pull_request") && node.hasDefined("labels")) { // Verify the labels aren't empty if (!node.get("labels").asList().isEmpty()) { // The key will be the PR URL resultIssues.get(node.get("pull_request", "url").asString()).set(node); } } } } catch (Exception e) { e.printStackTrace(err); } return resultIssues; }
From source file:com.predic8.membrane.core.interceptor.balancer.NodeOnlineChecker.java
private List<BadNode> pingOfflineNodes() { ArrayList<BadNode> onlineNodes = new ArrayList<BadNode>(); for (BadNode node : offlineNodes) { URL url = null;/* w ww .j a va 2 s . c om*/ try { url = new URL(node.getNode().getHost()); } catch (MalformedURLException ignored) { continue; } try { HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setConnectTimeout(pingTimeoutInSeconds * 1000); urlConn.connect(); if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) onlineNodes.add(node); } catch (IOException ignored) { continue; } } return onlineNodes; }
From source file:com.gdevelop.gwt.syncrpc.RemoteServiceSyncProxy.java
public Object doInvoke(RequestCallbackAdapter.ResponseReader responseReader, String requestData) throws Throwable { HttpURLConnection connection = null; InputStream is = null;//from w ww.j a va 2 s . c o m int statusCode; if (DUMP_PAYLOAD) { log.debug("Send request to {}", remoteServiceURL); log.debug("Request payload: {}", requestData); } // Send request CookieHandler oldCookieHandler = CookieHandler.getDefault(); try { CookieHandler.setDefault(cookieManager); URL url = new URL(remoteServiceURL); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty(RpcRequestBuilder.STRONG_NAME_HEADER, serializationPolicyName); connection.setRequestProperty(RpcRequestBuilder.MODULE_BASE_HEADER, moduleBaseURL); connection.setRequestProperty("Content-Type", "text/x-gwt-rpc; charset=utf-8"); connection.setRequestProperty("Content-Length", "" + requestData.getBytes("UTF-8").length); CookieStore store = cookieManager.getCookieStore(); String cookiesStr = ""; for (HttpCookie cookie : store.getCookies()) { if (!"".equals(cookiesStr)) cookiesStr += "; "; cookiesStr += cookie.getName() + "=" + cookie.getValue(); } connection.setRequestProperty("Cookie", cookiesStr); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(requestData); writer.flush(); writer.close(); } catch (IOException e) { throw new InvocationException("IOException while sending RPC request", e); } finally { CookieHandler.setDefault(oldCookieHandler); } // Receive and process response try { is = connection.getInputStream(); statusCode = connection.getResponseCode(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) > 0) { baos.write(buffer, 0, len); } String encodedResponse = baos.toString("UTF8"); if (DUMP_PAYLOAD) { log.debug("Response code: {}", statusCode); log.debug("Response payload: {}", encodedResponse); } // System.out.println("Response payload (len = " + encodedResponse.length() + "): " + encodedResponse); if (statusCode != HttpURLConnection.HTTP_OK) { throw new StatusCodeException(statusCode, encodedResponse); } else if (encodedResponse == null) { // This can happen if the XHR is interrupted by the server dying throw new InvocationException("No response payload"); } else if (isReturnValue(encodedResponse)) { encodedResponse = encodedResponse.substring(4); return responseReader.read(createStreamReader(encodedResponse)); } else if (isThrownException(encodedResponse)) { encodedResponse = encodedResponse.substring(4); Throwable throwable = (Throwable) createStreamReader(encodedResponse).readObject(); throw throwable; } else { throw new InvocationException("Unknown response " + encodedResponse); } } catch (IOException e) { log.error("error response: {}", IOUtils.toString(connection.getErrorStream())); throw new InvocationException("IOException while receiving RPC response", e); } catch (SerializationException e) { throw new InvocationException("Error while deserialization response", e); } finally { if (is != null) { try { is.close(); } catch (IOException ignore) { } } if (connection != null) { // connection.disconnect(); } } }
From source file:com.hortonworks.registries.auth.client.AuthenticatorTestCase.java
protected void _testAuthentication(Authenticator authenticator, boolean doPost) throws Exception { start();//from w w w . j a v a2s . co m try { URL url = new URL(getBaseURL()); AuthenticatedURL.Token token = new AuthenticatedURL.Token(); Assert.assertFalse(token.isSet()); TestConnectionConfigurator connConf = new TestConnectionConfigurator(); AuthenticatedURL aUrl = new AuthenticatedURL(authenticator, connConf); HttpURLConnection conn = aUrl.openConnection(url, token); Assert.assertTrue(connConf.invoked); String tokenStr = token.toString(); if (doPost) { conn.setRequestMethod("POST"); conn.setDoOutput(true); } conn.connect(); if (doPost) { Writer writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(POST); writer.close(); } Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); if (doPost) { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String echo = reader.readLine(); Assert.assertEquals(POST, echo); Assert.assertNull(reader.readLine()); } aUrl = new AuthenticatedURL(); conn = aUrl.openConnection(url, token); conn.connect(); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); Assert.assertEquals(tokenStr, token.toString()); } finally { stop(); } }
From source file:com.brobwind.brodm.NetworkUtils.java
public static void runCommand(HttpClient client, String token, String url, String cmd, OnMessage callback) { HttpPost request = new HttpPost(url); request.addHeader("Authorization", "Basic " + token); request.addHeader("Content-Type", "application/json"); try {/*from w ww.ja va2 s . co m*/ StringEntity content = new StringEntity(cmd); request.setEntity(content); } catch (UnsupportedEncodingException e) { e.printStackTrace(); callback.onMessage(null, e.getMessage()); return; } try { HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) { Log.v(TAG, " -> ABORT: " + response.getStatusLine()); request.abort(); callback.onMessage(null, "ABORT: " + response.getStatusLine()); return; } String result = EntityUtils.toString(response.getEntity()); Log.v(TAG, " -> RESULT: " + result); callback.onMessage(result, null); return; } catch (Exception e) { e.printStackTrace(); callback.onMessage(null, e.getMessage()); } }
From source file:com.streamsets.datacollector.http.TestWebServerTaskHttpHttps.java
@Test public void testHttp() throws Exception { Configuration conf = new Configuration(); int httpPort = getRandomPort(); conf.set(WebServerTask.AUTHENTICATION_KEY, "none"); conf.set(WebServerTask.HTTP_PORT_KEY, httpPort); final WebServerTask ws = createWebServerTask(createTestDir(), conf); try {// w ww .j av a 2s . c om ws.initTask(); new Thread() { @Override public void run() { ws.runTask(); } }.start(); Thread.sleep(1000); HttpURLConnection conn = (HttpURLConnection) new URL("http://127.0.0.1:" + httpPort + "/ping") .openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); } finally { ws.stopTask(); } }
From source file:net.sf.ehcache.constructs.web.filter.SimpleCachingHeadersPageCachingFilterTest.java
/** * HEAD methods return an empty response body. If a HEAD request populates * a cache and then a GET follorws, a blank page will result. * This test ensures that the SimplePageCachingFilter implements calculateKey * properly to avoid this problem./*from w w w .j a v a 2s . c o m*/ */ @Test public void testHeadThenGetOnCachedPage() throws Exception { HttpClient httpClient = new HttpClient(); HttpMethod httpMethod = new HeadMethod(buildUrl(cachedPageUrl)); int responseCode = httpClient.executeMethod(httpMethod); //httpclient follows redirects, so gets the home page. assertEquals(HttpURLConnection.HTTP_OK, responseCode); String responseBody = httpMethod.getResponseBodyAsString(); assertNull(responseBody); assertNull(httpMethod.getResponseHeader("Content-Encoding")); httpMethod = new GetMethod(buildUrl(cachedPageUrl)); responseCode = httpClient.executeMethod(httpMethod); responseBody = httpMethod.getResponseBodyAsString(); assertNotNull(responseBody); }
From source file:com.stackmob.example.CreateUnverifiedUser.java
@Override public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) { String username = ""; String email = ""; // SendGrid Vars String API_USER = ""; String API_KEY = ""; String subject = "New User Verification "; String text = ""; String from = "sid@stackmob.com"; String to = ""; String toname = ""; String body = ""; String url = ""; LoggerService logger = serviceProvider.getLoggerService(CreateUnverifiedUser.class); //Log the JSON object passed to the StackMob Logs logger.debug(request.getBody());//from w ww. j a v a 2s . co m // I'll be using these maps to print messages to console as feedback to the operation Map<String, SMValue> feedback = new HashMap<String, SMValue>(); Map<String, String> errMap = new HashMap<String, String>(); try { API_USER = serviceProvider.getConfigVarService().get("SENDGRID_USERNAME", "sendgrid"); API_KEY = serviceProvider.getConfigVarService().get("SENDGRID_PASSWORD", "sendgrid"); } catch (Exception e) { return Util.internalErrorResponse("configvar_service_exception", e, errMap); // error 500 } JSONParser parser = new JSONParser(); try { Object obj = parser.parse(request.getBody()); JSONObject jsonObject = (JSONObject) obj; //We use the username passed to query the StackMob datastore //and retrieve the user's name and email address username = (String) jsonObject.get("username"); email = (String) jsonObject.get("email"); } catch (ParseException e) { return Util.internalErrorResponse("parse_exception", e, errMap); // error 500 } if (Util.hasNulls(username)) { return Util.badRequestResponse(errMap); } // get the StackMob datastore service and assemble the query DataService dataService = serviceProvider.getDataService(); SMObject newUserObject; SMObject newUserVerifyObject; String uuid = UUID.randomUUID().toString(); try { // create new unverified user query Map<String, SMValue> objUserVerifyMap = new HashMap<String, SMValue>(); objUserVerifyMap.put("username", new SMString(username)); objUserVerifyMap.put("email", new SMString(email)); objUserVerifyMap.put("uuid", new SMString(uuid)); newUserObject = dataService.createObject("user_unverified", new SMObject(objUserVerifyMap)); feedback.put("user_unverified", new SMString(newUserObject.toString())); text = "Welcome to my App! <br/><br/>Please <a href='http://localhost:4567/#verify/" + username + "/" + uuid + "'>Verify Your Account and Create a Password</a>"; } catch (InvalidSchemaException e) { return Util.internalErrorResponse("invalid_schema", e, errMap); // error 500 // http 500 - internal server error } catch (DatastoreException e) { return Util.internalErrorResponse("datastore_exception", e, errMap); // http 500 - internal server error } catch (Exception e) { return Util.internalErrorResponse("unknown_exception", e, errMap); // http 500 - internal server error } if (Util.hasNulls(subject)) { return Util.badRequestResponse(errMap); // http 400 bad response } //Encode any parameters that need encoding (i.e. subject, toname, text) try { subject = URLEncoder.encode(subject, "UTF-8"); text = URLEncoder.encode(text, "UTF-8"); toname = URLEncoder.encode(toname, "UTF-8"); } catch (UnsupportedEncodingException e) { return Util.internalErrorResponse("unsupported_encoding_exception", e, errMap); // http 500 - internal server error } String queryParams = "api_user=" + API_USER + "&api_key=" + API_KEY + "&to=" + email + "&toname=" + username + "&subject=" + subject + "&html=" + text + "&from=" + from; url = "https://www.sendgrid.com/api/mail.send.json?" + queryParams; Header accept = new Header("Accept-Charset", "utf-8"); Header content = new Header("Content-Type", "application/x-www-form-urlencoded"); Set<Header> set = new HashSet(); set.add(accept); set.add(content); try { HttpService http = serviceProvider.getHttpService(); PostRequest req = new PostRequest(url, set, body); HttpResponse resp = http.post(req); feedback.put("email_response", new SMString(resp.getBody())); } catch (TimeoutException e) { return Util.internalErrorResponse("internal_error_response", e, errMap); // http 500 - internal server error } catch (AccessDeniedException e) { return Util.internalErrorResponse("access_denied_exception", e, errMap); // http 500 - internal server error } catch (MalformedURLException e) { return Util.internalErrorResponse("malformed_url_exception", e, errMap); // http 500 - internal server error } catch (ServiceNotActivatedException e) { return Util.internalErrorResponse("service_not_activated_exception", e, errMap); // http 500 - internal server error } return new ResponseToProcess(HttpURLConnection.HTTP_OK, feedback); }