@Test public void whenSignUpTwiceWithSameEmail_shouldFailOnSecondSignUp() throws Exception { HttpRequest signUpRequest = signUpRequest("*****@*****.**", "pass"); assertThat(signUpRequest.code()).isEqualTo(CREATED.getStatusCode()); HttpRequest signUpRequest2 = signUpRequest("*****@*****.**", "pass"); assertThat(signUpRequest2.code()).isEqualTo(CONFLICT.getStatusCode()); }
@Override public ActionPlan create(NewActionPlan newActionPlan) { HttpRequest request = requestFactory.post(NewActionPlan.BASE_URL, newActionPlan.urlParams()); if (!request.ok()) { throw new IllegalStateException( "Fail to create action plan. Bad HTTP response status: " + request.code()); } return createActionPlanResult(request); }
private HttpRequest executeSimpleAction(String actionPlanKey, String action) { HttpRequest request = requestFactory.post( "/api/action_plans/" + action, EncodingUtils.toMap("key", actionPlanKey)); if (!request.ok()) { throw new IllegalStateException( "Fail to " + action + " action plan. Bad HTTP response status: " + request.code()); } return request; }
/** @see org.sonar.process.test.HttpProcess */ boolean isReady() { try { HttpRequest httpRequest = HttpRequest.get("http://localhost:" + httpPort + "/" + "ping") .readTimeout(2000) .connectTimeout(2000); return httpRequest.ok() && httpRequest.body().equals("ping"); } catch (HttpRequest.HttpRequestException e) { return false; } }
private HttpRequest configure(final HttpRequest request) { request.connectTimeout(TIMEOUT).readTimeout(TIMEOUT); request.userAgent(userAgentProvider.get()); if (isPostOrPut(request)) { // All PUT & POST requests to Parse.com api must be in JSON // https://www.parse.com/docs/rest#general-requests request.contentType(Constants.Http.CONTENT_TYPE_JSON); } return addCredentialsTo(request); }
public void restart() { try { HttpRequest httpRequest = HttpRequest.post("http://localhost:" + httpPort + "/" + "restart") .readTimeout(5000) .connectTimeout(5000); if (!httpRequest.ok() || !"ok".equals(httpRequest.body())) { throw new IllegalStateException("Wrong response calling restart"); } } catch (Exception e) { throw new IllegalStateException("Failed to call restart", e); } }
@Test public void testFind() throws Exception { expect(client.get("products/70")).andReturn(request); expect(request.code()).andReturn(200); expect(request.body()).andReturn(productResponse(true)); replayAll(); Response<Product> response = Product._find(client, 70); Product product = response.getResource(); assertEquals("Wrong product name", "Basic", product.getName()); assertEquals("Wrong product handle", "basic", product.getHandle()); }
private HttpRequest createRequest(String source) { HttpRequest request = HttpRequest.get(source); // Add credentials if a secure connection to github.com HttpURLConnection connection = request.getConnection(); if (connection instanceof HttpsURLConnection && HOST_DEFAULT.equals(connection.getURL().getHost())) { Account account = AccountUtils.getAccount(context); if (account != null) { String password = AccountManager.get(context).getPassword(account); if (!TextUtils.isEmpty(password)) request.basic(account.name, password); } } return request; }
@Override // 1.data 통신 public ArrayList<String> call() throws Exception { JSONResultString result = null; ArrayList<String> arrayList1 = new ArrayList<String>(); try { HttpRequest request = post("http://192.168.0.5:8088/bitin/api/class/start-attd "); // reiquest 설정 request.connectTimeout(2000).readTimeout(2000); // JSON 포맷으로 보내기 => POST 방식 request.acceptCharset("UTF-8"); request.acceptJson(); request.accept(HttpRequest.CONTENT_TYPE_JSON); request.contentType("application/json", "UTF-8"); // 데이터 세팅 JSONObject params1 = new JSONObject(); params1.put("classNo", classNo); params1.put("startTime", endTime); params1.put("timer", count_timer); Log.d("JoinData-->", params1.toString()); request.send(params1.toString()); // 3. 요청 int responseCode = request.code(); if (HttpURLConnection.HTTP_OK != responseCode) { Log.e("HTTP fail-->", "Http Response Fail:" + responseCode); return null; } else { Log.e("HTTPRequest-->", "정상"); } // 4. JSON 파싱 Reader reader = request.bufferedReader(); // Log.d("Reader",reader); result = GSON.fromJson(reader, JSONResultString.class); reader.close(); // 5. 사용하기 Log.d("---> ResponseResult-->", result.getResult()); // "success"? or "fail"? Log.d("--->Data-->", result.getData().toString()); return result.getData(); } catch (Exception e3) { e3.printStackTrace(); } return result.getData(); }
@Override public void run() { try { HttpRequest request = HttpRequest.put(this.getUrlString()); this.setupSecurity(request); request.acceptCharset(CHARSET); request.headers(this.getHeaders()); request.form(this.getParams()); int code = request.code(); String body = request.body(CHARSET); JSONObject response = new JSONObject(); response.put("status", code); if (code >= 200 && code < 300) { response.put("data", body); this.getCallbackContext().success(response); } else { response.put("error", body); this.getCallbackContext().error(response); } } catch (JSONException e) { this.respondWithError("There was an error generating the response"); } catch (HttpRequestException e) { if (e.getCause() instanceof UnknownHostException) { this.respondWithError(0, "The host could not be resolved"); } else if (e.getCause() instanceof SSLHandshakeException) { this.respondWithError("SSL handshake failed"); } else { this.respondWithError("There was an error with the request"); } } }
private HttpRequest signOutRequest(String token) { Map<String, String> formParameters = new HashMap<>(); if (token != null) { formParameters.put("token", token); } return HttpRequest.post(CONTAINER_URL + PATH + "out") .contentType("application/x-www-form-urlencoded") .form(formParameters); }
private HttpRequest addCredentialsTo(final HttpRequest request) { // Required params for request.header(HEADER_PARSE_REST_API_KEY, PARSE_REST_API_KEY); request.header(HEADER_PARSE_APP_ID, PARSE_APP_ID); /* * NOTE: This may be where you want to add a header for the api token that was saved when * you logged in. In the bootstrap sample this is where we are saving the session id as * the token. If you actually had received a token you'd take the "apiKey" (aka: token) * and add it to the header or form values before you make your requests. * * Add the user name and password to the request here if your service needs username or * password for each request. You can do this like this: * request.basic("myusername", "mypassword"); */ return request; }
@Override public List<ActionPlan> find(String projectKey) { HttpRequest request = requestFactory.get(ActionPlanQuery.BASE_URL, EncodingUtils.toMap("project", projectKey)); if (!request.ok()) { throw new IllegalStateException( "Fail to search for action plans. Bad HTTP response status: " + request.code()); } List<ActionPlan> result = new ArrayList<ActionPlan>(); String json = request.body("UTF-8"); Map jsonRoot = (Map) JSONValue.parse(json); List<Map> jsonActionPlans = (List) jsonRoot.get("actionPlans"); if (jsonActionPlans != null) { for (Map jsonActionPlan : jsonActionPlans) { result.add(new ActionPlan(jsonActionPlan)); } } return result; }
/** @see org.sonar.process.test.HttpProcess */ void kill() { try { HttpRequest.post("http://localhost:" + httpPort + "/" + "kill") .readTimeout(5000) .connectTimeout(5000) .ok(); } catch (Exception e) { // HTTP request can't be fully processed, as web server hardly // calls "System.exit()" } }
public Drawable getDrawable(String source) { File output = null; try { output = File.createTempFile("image", ".jpg", dir); HttpRequest request = createRequest(source); if (!request.ok()) throw new IOException("Unexpected response code: " + request.code()); request.receive(output); Bitmap bitmap = ImageUtils.getBitmap(output, width, MAX_VALUE); if (bitmap == null) return loading.getDrawable(source); BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap); drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); return drawable; } catch (IOException e) { return loading.getDrawable(source); } catch (HttpRequestException e) { return loading.getDrawable(source); } finally { if (output != null) output.delete(); } }
/** * Get all bootstrap Users that exist on Parse.com * * @return non-null but possibly empty list of bootstrap * @throws IOException */ public List<User> getUsers() throws IOException { try { final HttpRequest request = execute(HttpRequest.get(URL_USERS)); final UsersWrapper response = fromJson(request, UsersWrapper.class); if (response != null && response.results != null) { return response.results; } return Collections.emptyList(); } catch (final HttpRequestException e) { throw e.getCause(); } }
/** * Get all bootstrap Checkins that exists on Parse.com * * @return non-null but possibly empty list of bootstrap * @throws IOException */ public List<CheckIn> getCheckIns() throws IOException { try { final HttpRequest request = execute(HttpRequest.get(URL_CHECKINS)); final CheckInWrapper response = fromJson(request, CheckInWrapper.class); if (response != null && response.results != null) { return response.results; } return Collections.emptyList(); } catch (final HttpRequestException e) { throw e.getCause(); } }
public static String getJSONFromUrl(Activity activity, String url) throws CustomException { String json; // defaultHttpClient try { json = HttpRequest.get(url).body(); if (json != null && json.contains("listeSerie")) { FileUtils.saveContent(activity, json); } } catch (HttpRequest.HttpRequestException e) { } json = FileUtils.loadFile(activity); // return JSON String return json; }
private <V> V fromJson(final HttpRequest request, final Class<V> target) throws IOException { final Reader reader = request.bufferedReader(); try { return GSON.fromJson(reader, target); } catch (final JsonParseException e) { throw new JsonException(e); } finally { try { if (reader != null) { reader.close(); } } catch (final IOException ignored) { // Ignored } } }
@Test public void signOut_shouldReturnTrue_ifSignsOutBeingSignedIn() throws Exception { HttpRequest signUpRequest = signUpRequest("*****@*****.**", "pass"); assertThat(signUpRequest.code()).isEqualTo(CREATED.getStatusCode()); String token = signUpRequest.body().toString(); assertThat(token).isNotEmpty(); HttpRequest signOutRequest = signOutRequest(token); assertThat(signOutRequest.code()).isEqualTo(OK.getStatusCode()); assertThat(signOutRequest.body()).isEqualTo("true"); }
/** * Makes HTTP get request and parses the responses JSON into HashMaps. * * @throws IOException */ private void getData() throws IOException { String json = HttpRequest.get(URL).body(); JsonFactory factory = new JsonFactory(); JsonParser parser = factory.createJsonParser(json); Map<String, Object> region = null; parser.nextToken(); while (parser.nextToken() == JsonToken.START_OBJECT) { region = mapper.readValue(parser, new TypeReference<Map<String, Object>>() {}); if (region.containsKey(CATEGORY_FIELD)) { if (REGION_CATEGORY.equals(region.get(CATEGORY_FIELD))) { regionsByCode.put((String) region.get(CODE_FIELD), (Integer) region.get(ID_FIELD)); regionsById.put((Integer) region.get(ID_FIELD), (String) region.get(CODE_FIELD)); } } } }
protected String doInBackground(String... urls) { String response = null; try { String url = "http://" + urls[0] + "/index.php"; Log.d("myTag", url); response = HttpRequest.post(url).accept("application/json").form(userData).body(); Log.d("myTag", "Response-->" + response); } catch (HttpRequest.HttpRequestException exception) { Log.d("myTag", "HttpRequest Exception"); return null; } catch (Exception e) { e.printStackTrace(); return null; } return response; }
protected String doInBackground(String... urls) { String response = null; try { String url = "http://" + urls[0] + "/action.php"; Log.d("myTag", url); response = HttpRequest.post(url).accept("application/json").form(userData).body(); Log.d("myTag", "Response-->" + response); } catch (HttpRequest.HttpRequestException exception) { Log.d("myTag", "HttpRequest Exception"); Toast.makeText( getApplicationContext(), "GCM server registration failed", Toast.LENGTH_SHORT) .show(); return null; } catch (Exception e) { e.printStackTrace(); Toast.makeText( getApplicationContext(), "GCM server registration failed", Toast.LENGTH_SHORT) .show(); return null; } return response; }
@Override public void onCreate() { // OkHttp changes the global SSL context, breaks other HTTP clients. Google Analytics uses a // different http // client, which OkHttp doesn't handle well. // https://github.com/square/okhttp/issues/184 if (!mUrlStreamFactorySet) { URL.setURLStreamHandlerFactory(Utils.createOkHttpClient()); mUrlStreamFactorySet = true; } // Use OkHttp instead of HttpUrlConnection to handle HTTP requests, OkHttp supports 2.2 while // HttpURLConnection // is a bit buggy on froyo. if (!mConnectionFactorySet) { HttpRequest.setConnectionFactory(new OkConnectionFactory()); mConnectionFactorySet = true; } super.onCreate(); sMainApplication = this; setSite(getDefaultSite()); }
@Test public void signOut_shouldReturnFalse_ifSignsOutWithoutBeingSignedIn() throws Exception { HttpRequest signOutRequest = signOutRequest("TOKEN"); assertThat(signOutRequest.code()).isEqualTo(UNAUTHORIZED.getStatusCode()); assertThat(signOutRequest.body()).isEqualTo("false"); }
/** Create main application */ public BootstrapApplication() { // Disable http.keepAlive on Froyo and below if (SDK_INT <= FROYO) { HttpRequest.keepAlive(false); } }
@Test public void signUp_shouldCreateAnUser() throws Exception { HttpRequest signUpRequest = signUpRequest("*****@*****.**", "pass"); assertThat(signUpRequest.code()).isEqualTo(CREATED.getStatusCode()); }
@Test public void signIn_shouldReturnBadRequestStatusCode_ifNullParameters() throws Exception { HttpRequest signInRequest = signInRequest("", ""); assertThat(signInRequest.code()).isEqualTo(BAD_REQUEST.getStatusCode()); }
@Test public void signIn_shouldReturnUnauthorizedStatusCode_ifNotLoggedIn() throws Exception { HttpRequest signInRequest = signInRequest("notLoggedInEmail", "pass"); assertThat(signInRequest.code()).isEqualTo(UNAUTHORIZED.getStatusCode()); }
private HttpRequest signInRequest(String emailValue, String passValue) { return HttpRequest.post(CONTAINER_URL + PATH + "in") .contentType("application/x-www-form-urlencoded") .form(getFormParameters(emailValue, passValue)); }