I have upgraded angular 4 to 6 and I used RequestOptions to send data with http delete request like this
return this.http.delete(Config.apiUrl, new RequestOptions({
headers: this.heders,
body: data
})).map(res=>res.json());
now after upgraded I cant find RequestOptions
import process in angular 4
import { Http, Headers, RequestOptions } from '#angular/http';
import process in angular 6
import { HttpClient, HttpHeaders} from '#angular/common/http';
any idea ?
HttpClient.prototype.delete() is overloaded.
The easiest way is to pass a plain object:
return this.http.delete(Config.apiUrl, {
headers: this.heders,//misspelt
body: data
}).map(res=>res.json());
Additionally, if you wanted more control over the request, you could construct an HttpRequest and pass it to HttpClient.prototype.request().
Related
How can i fetch JSON data without key in flutter?
I don't need to create a map to fetch it, i have an url to call it and the json is composed of one single int value. How can i fetch it?
var client = http.Client();
String url = "url";
Response response = await client.get(url);
print('Response status: ${response.statusCode}');
print('Response body: ${json.decode((response.body))}');
There is package called http that can help you to fetch data from your API
so this how you proceed
import http package
import 'package:http/http.dart';
then send request to your API by
Response response = await get(url); this is a asynchronous methosd so make sure to add async in your function
So, as you asked you don't want to create Map variable
this is how you access it
int x = jsonDecode(response.body)['the key']
make sure you import import 'dart:convert'; as it a dependency
if you still have issues comment down below.
Regards,
Roshan
So I was trying to follow this example:
Spring REST Docs: how to replace parameters
What I'm trying to do is to mask the JWT token in the header of my request and I have an OperationPreprocessor that looks like this:
import org.springframework.http.HttpHeaders
import org.springframework.restdocs.operation.OperationRequest
import org.springframework.restdocs.operation.OperationRequestFactory
import org.springframework.restdocs.operation.OperationResponse
import org.springframework.restdocs.operation.preprocess.OperationPreprocessor
class AuthHeaderPreprocessor implements OperationPreprocessor {
#Override
OperationRequest preprocess(OperationRequest request) {
HttpHeaders headers = new HttpHeaders()
headers.putAll(request.getHeaders())
headers.set('Authorization', 'Bearer 12345')
return new OperationRequestFactory().create(
request.getUri(),
request.getMethod(),
request.getContent(),
headers,
request.getParameters(),
request.getParts()
)
}
#Override
OperationResponse preprocess(OperationResponse response) {
return response
}
}
When I run the test they run without error but I don't see any change to the header. I'm using the OperationPreprocessor like this
RestAssuredRestDocumentation.document(
'event-list', preprocessRequest(new AuthHeaderPreprocessor()), ...
Any ideas what I may be missing.
The code I had actually worked and is a good example of how to filter headers. For some reason when testing it initially I wasn't working, but that seems like it was maybe just something cached in the build not getting cleared, as it works now.
I have an issue about POST data at add student page. I'm using ionic 3 and backend API restful laravel, I tried this POST in postman and it's works, but I got an error message "invalid token or token not provided" after click Add button (refer the first picture). I'm not sure how to write method with auth token.
You can refer my provider (second image) ,addstudent.ts (third image), button html (forth image) for reference
Thanks in advance.
Suppose you stored your token in a storage (e.g localStorage or sessionStorage), you can do the following:
Step1: Add Auth provider and extend BaseRequestOptions
import { BaseRequestOptions, RequestOptions, RequestOptionsArgs } from '#angular/http';
import { Injectable } from '#angular/core';
#Injectable()
export class AuthProvider extends BaseRequestOptions {
constructor() {
super();
this.headers.set('Content-Type', 'application/json');
}
merge(options?: RequestOptionsArgs): RequestOptions {
let newOptions = super.merge(options);
let accessToken = localStorage.getItem('accessToken');
if (accessToken !== null && accessToken !== undefined) {
let token: AcessTokenResponse = JSON.parse(accessToken);
newOptions.headers.set('Authorization', token.token_type + ' ' + token.access_token);
}
return newOptions;
}
}
Step2: Add AuthProvider under providers in app.module.ts file
As per my exprience you need to add RequestOptions in your POST call like below:
let options = new RequestOptions({
headers: headers
});
this.http.post(this.apiUrl+'/addstudent', addStudent, options)
As in your code you are creating Header but not passing it into post request.
Try above code Hope this will help you to get your API work.
I am trying to upload a video to s3 and have a pre-signed PUT url. The following is the code to do so.
import {Component} from '#angular/core';
import {NavController} from 'ionic-angular';
import {MediaCapture} from 'ionic-native';
import {Http} from '#angular/http';
import { Transfer } from 'ionic-native';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public base64Image: string;
constructor(private navController: NavController, public http: Http) {
this.base64Image = "https://placehold.it/150x150";
}
public takeVideo() {
MediaCapture.captureVideo({limit:2}).then(function(videoData){
var link = "https://mysamplebucket.s3.amazonaws.com/non-tp/esx.mov?AWSAccessKeyId=TEMP_KEYY&Expires=1482290587&Signature=JUIHHI%2FcnLkqSVg%3D&x-amz-security-token=FQoDYXDGRfTXk6hma0Rxew6yraAX%2FlYGaQmYLwkvsuuB3%2F%2FtPvGDVs3dIQG0Ty3MeMjn0p%%26djt5xhAMk73pndJbZP0tCYYlvPvlUAyL8x7O%%2B3AwEa%%2B9b43yarIuPLCvujmKLTDyi%%3D%3Di";
var options: any;
options = {
fileKey: 'file',
fileName: 'esx.mov',
httpMethod: 'PUT',
chunkedMode: false,
mimeType: 'video/quicktime',
encodeURI: false,
headers: {
'Content-Type': 'video/quicktime'
}
};
var ft = new Transfer();
ft.upload(videoData[0].fullPath, link, options, false)
.then((result: any) => {
this.success(result);
}).catch((error: any) => {
this.failed(error);
});
}, function(err){
alert(err);
});
}
}
Here is the code that generates the pre-signed PUT url.
var params = {Bucket: s3_bucket, Key: filename, Expires: 900000};
var url = {
'url' : s3.getSignedUrl('putObject', params)
};
I get, SignatureDoesNotMatch error. The message says, The request signature we calculated does not match the signature you provided. Check your key and signing method. I am not sure what I am doing wrong here - I looked a few other SO and Ionic questions and tried what they recommended to no avail. Any ideas on what I and doing wrong?
Your upload PUT request will have a Content-Type: video/quicktime header.
When the Content-Type header is present in the request (not the response), its value is a non-optional component in the Signature V2 canonical request... which means you have to pass it to the code generating the signature.
var params = {Bucket: s3_bucket, Key: filename, Expires: 900000}; also needs this string (video/quicktime, in this case) passed to it as ContentType: ... for a PUT request (but not for a GET request, since this describes the content you are sending, and GET requests customarily send no actual content.
The SDK documentation doesn't seem to specifically mention this, but it is most definitely required by S3.
In case someone else is looking at this and is in a similar situation as me, I got a similar SignatureDoesNotMatchError when my s3 bucket's CORS Configuration did not contain <AllowedHeader>*</AllowedHeader>
I ran into this when moving from one bucket to another, copying all the settings except for the CORS Configuration.
We faced this issue when we were downloading an already uploaded file. We were receiving the presigned url, but when tried to download the file with that presign url, it said "signature does not match".
The solution we received when we reported a ticket with AWS because all the approaches failed. The scenario is we have our custom AWS KMS encryption enabled for S3 bucket, but we were trying to send "kms key" along with our request when using GeneratePresignedUrlRequest api. AWS said, we don't have to send KMS key, instead send without encrypting from client. When I say unencrypted, it is not exactly that, it is already coming in encrypted form and when we were using "AWSS3V4SignerType" to sign, we were sending kms id as an additional param that wasn't required to begin with. Hope this makes sense.
The params AWS looks for in the header are:
Algorithm
Credential Scope
Signed headers
Date
Expiration Date
Signature
KMS Key - we were passing this, which wasn't required.
I'm evaluating the possibility of using Play2-mini with Scala to develop a service that will sit between a mobile client and existing web service. I'm looking for the simplest possible example of a piece of code where Play2-mini implements a server and a client. Ideally the client will use Akka2 actors.
With this question, I'm trying to find out how it is done, but also to see how Play2-Mini and Akka2 should co-operate. Since Play2-Mini appears to be the replacement for the Akka HTTP modules.
Play2-mini contains the following code example, in which I created two TODO's. If someone can help me with some sample code to get started, I will be really grateful.
package com.example
import com.typesafe.play.mini._
import play.api.mvc._
import play.api.mvc.Results._
object App extends Application {
def route = {
case GET(Path("/testservice")) & QueryString(qs) => Action{ request=>
println(request.body)
//TODO Take parameter and content from the request them pass it to the back-end server
//TODO Receive a response from the back-end server and pass it back as a response
Ok(<h1>Server response: String {result}</h1>).as("text/html")
}
}
}
Here's the implementation of your example.
Add the following imports:
import play.api.libs.ws.WS
import play.api.mvc.BodyParsers.parse
import scala.xml.XML
Add the following route:
case GET(Path("/testservice")) & QueryString(qs) => Action{ request =>
Async {
val backendUrl = QueryString(qs,"target") map (_.get(0)) getOrElse("http://localhost:8080/api/token")
val tokenData = QueryString(qs,"data") map (_.get(0)) getOrElse("<auth>john</auth>")
WS.url(backendUrl).post(XML loadString tokenData).map { response =>
Ok(<html><h1>Posted to {backendUrl}</h1>
<body>
<div><p><b>Request body:</b></p>{tokenData}</div>
<div><p><b>Response body:</b></p>{response.body}</div>
</body></html>).as("text/html") }
}
}
All it does, is forwarding a GET request to a back-end serivce as a POST request. The back-end service is specified in the request parameter as target and the body for the POST request is specified in the request parameter as data (must be valid XML). As a bonus the request is handled asynchronously (hence Async). Once the response from the back-end service is received the front-end service responds with some basic HTML showing the back-end service response.
If you wanted to use request body, I would suggest adding the following POST route rather than GET (again, in this implementation body must be a valid XML):
case POST(Path("/testservice")) & QueryString(qs) => Action(parse.tolerantXml){ request =>
Async {
val backendUrl = QueryString(qs,"target") map (_.get(0)) getOrElse("http://localhost:8080/api/token")
WS.url(backendUrl).post(request.body).map { response =>
Ok(<html><h1>Posted to {backendUrl}</h1>
<body>
<div><p><b>Request body:</b></p>{request.body}</div>
<div><p><b>Response body:</b></p>{response.body}</div>
</body></html>).as("text/html") }
}
}
So as you can see, for your HTTP Gateway you can use Async and play.api.libs.ws.WS with Akka under the hood working to provide asynchronous handling (no explicit Actors required). Good luck with your Play2/Akka2 project.
Great answer by romusz
Another way to make a (blocking) HTTP GET request:
import play.api.libs.ws.WS.WSRequestHolder
import play.api.libs.ws.WS.url
import play.api.libs.concurrent.Promise
import play.api.libs.ws.Response
val wsRequestHolder: WSRequestHolder = url("http://yourservice.com")
val promiseResponse: Promise[Response] = wsRequestHolder.get()
val response = promiseResponse.await.get
println("HTTP status code: " + response.status)
println("HTTP body: " + response.body)