I have an android device and I'm trying to make a web app that will communicate with it (send json etc.).
I have made an api service that will send either a post or HttpRequest but I got stuck because I'm getting errors like bad request and connection failed. Both my notebook and the android are connected to the same wifi wirelessly and the android device is connected on a static ip address.
Here is my api service:
public post<T>(endpoint: string, params = null, headers?): Observable<T> {
return this.http.post<T>('http://' + endpoint, params, headers ? headers : {headers: this.getRequestHeaders()})
.pipe(httpRetry(), tap(null, err => this.interceptError(err)));
}
public request<T>(method, endpoint: string, data, headers?: HttpHeaders) {
return this.http.request<T>(method, endpoint, {
body: data,
headers: headers
});
}
And here is my component using those functions:
sendRequest() {
this.apiService.request('string', this.basic.controls.ENDPOINT.value, this.selectedFile, this.getHeaders(true))
.subscribe((response: HttpResponse<any>) => this.response = response);
}
sendPost() {
this.apiService.post(this.basic.controls.ENDPOINT.value, this.selectedFile, this.getHeaders(true))
.subscribe((response: HttpResponse<any>) => this.response = response);
}
getHeaders( isMultipart: boolean = false,
acceptableMimeType: string = ApiService.DEFAULT_ACCEPTABLE_MIME_TYPE,
anonymous: boolean = false): HttpHeaders {
const Authorization = btoa(this.basic.controls.PASSWORD.value + this.basic.controls.USERNAME.value);
const headers = {
'X-Host-Override': '192.168.0.42',
'Content-Type': 'application/json',
'Content-Length': '120', // TODO add logic for correct content length
'Authorization': Authorization
};
if (!isMultipart) {
headers['Content-Type'] = 'application/json';
}
return new HttpHeaders(headers);
}
The endpoint is set to 192.168.0.42 and the port to 8080 (I also have no idea what port number to use). Also they are sending a json file thus the this.selected file.
this is my logic for sending the request:
const endpoint = 192.168.0.42:8200
const requestJson = someJson.json
this.apiService.post(endpoint, requestJson).subscribe(data => do something with data)
public post<T>(endpoint: string, params = null): Observable<T> {
return this.http.post<T>('http://' + endpoint, params, {headers: this.getRequestHeaders()})
.pipe(httpRetry(), tap(null, err => this.interceptError(err)));
}
And this is how I get my headers:
public getRequestHeaders(
isMultipart: boolean = false,
acceptableMimeType: string = ApiService.DEFAULT_ACCEPTABLE_MIME_TYPE,
anonymous: boolean = false
): HttpHeaders {
const headers = {
'Accept': acceptableMimeType,
observe: 'response'
};
if (!isMultipart) {
headers['Content-Type'] = 'application/json';
}
if (!anonymous) {
headers['Authorization'] = 'Basic ' + btoa(JSON.parse(localStorage.getItem('connectionData')).USERNAME + ':' + JSON.parse(localStorage.getItem('connectionData')).PASSWORD);
}
return new HttpHeaders(headers);
}