I am trying to save my data to DB using Spring Restful web services.
I am continuously getting unsupported media type error when I run this code in Postman.
I have edited my code with front end JSP code and Repository class..
I have also added jackson dependency in pom.xml file. I am not able to figure out what's wrong with my code as I am a newbie towards Restful web services.
Controller::
#RequestMapping(value="/insp_rep/{id}",method=RequestMethod.POST, headers = "Accept=application/json" )
ResponseEntity <Void> addRepo(#RequestBody PC_Repo report, #PathVariable("id") int id){
this.pmService.addRep(report);
return new ResponseEntity<Void>(HttpStatus.CREATED);
}
JSP Code along with AngularJS script
<html data-ng-app="formSubmit">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('formSubmit', []);
app.controller('FormSubmitController',[ '$scope', '$http', function($scope, $http) {
$scope.list = [];
$scope.headerText = 'Inspection Report';
$scope.submit = function() {
var formData = {
"ins_id": $scope.ins_id,
"date_insp": $scope.date_insp,
"bedrooms":$scope.bedrooms,
"balcony":$scope.balcony,
"kitchen":$scope.kitchen,
"bath_toilet":$scope.bath_toilet,
"parking_gar":$scope.parking_gar,
"garden":$scope.garden,
"others":$scope.others,
"action":$scope.action
};
var response = $http.post('/PM/insp_rep/{id}', formData);
response.success(function(data, status, headers, config) {
$scope.list.push(data);
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
//Empty list data after process
$scope.list = [];
};
}]);
</script>
Repository Class
#Entity
#JsonIgnoreProperties({"hibernateLazyInitializer","handler"})
#Table(name="abc")
public class abc implements Serializable {
private java.sql.Date date_insp;
private String bedrooms;
private String balcony;
private String kitchen;
private String bath_toilet;
private String parking_gar;
private String garden;
private String others;
private String title;
private byte[]photo;
As per explained above in the comments section, obj consists of all the form parameters submitted and passed to the controller.
JSP HTML Tag:
<input type="text" ng-model="obj.balcony" />
<input type"text" ng-model="obj.address" />
And in controller, try debugging the object value using alert and to convert the object in String use 'JSON.Stringify(obj)'.
Controller JS:
$scope.submit = function() {
var formData = $scope.obj;
alert(JSON.stringify($scope.obj));
var response = $http.post('/PM/insp_rep/{id}', JSON.Stringify(obj));
response.success(function(data, status, headers, config) {
$scope.list.push(data);
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
//Empty list data after process
$scope.list = [];
};
}]);
</script>
Related
I am trying to send a stream (containing an image file) from a WASM client to a backend .NET Core 5 server. In the WASM app, I start with a MemoryStream that contains the file data. In order to send the data contained in this MemoryStream using HttpClient.PostAsync, I seem to have to convert it to a StreamContent object:
StreamContent streamContent = new StreamContent(imageMemoryStream);
I use the debugger to verify that the length of the content of streamContent is not zero at this point. So far so good.
I then use HttpClient.PostAsync to send this stream to the server:
var response = await Http.PostAsync("api/HttpStreamReceiver", streamContent);
On the server side, I have a controller that receives HTTP messages:
[Route("api/[controller]")]
[ApiController]
public class HttpStreamReceiverController : ControllerBase
{
[HttpPost]
public async Task<ActionResult> Get()
{
Stream imageStream;
try
{
imageStream = Request.Body;
}
catch (Exception)
{
return new BadRequestObjectResult("Error saving file");
}
}
}
Here, it seems that Request.Body is empty. Trying to evaluate the length of either Request.Body or of imageStream on the server side results in a System.NotSupportedException, and
await imageStream.ReadAsync(buffer);
leaves buffer blank. What am I doing wrong here?
The image file cannot be transmitted through the body unless it is serialized. I suggest you use MultipartFormDataContent to pass the file.
This is an example.
class Program
{
static async Task Main(string[] args)
{
string filePath = #"D:\upload\images\1.png";
HttpClient _httpClient = new HttpClient();
string _url = "https://localhost:44324/api/HttpStreamReceiver/";
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (!File.Exists(filePath))
{
throw new FileNotFoundException($"File [{filePath}] not found.");
}
//Create form
using var form = new MultipartFormDataContent();
FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
byte[] buffur = new byte[fs.Length];
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buffur);
//var bytefile = AuthGetFileData(filePath);
var fileContent = new ByteArrayContent(buffur);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
form.Add(fileContent, "image", Path.GetFileName(filePath));
//the other data in form
var response = await _httpClient.PostAsync($"{_url}", form);
response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsStringAsync();
bw.Close();
}
}
Web api.
[Route("api/[controller]")]
[ApiController]
public class HttpStreamReceiverController: ControllerBase
{
[HttpPost]
public async Task<ActionResult> Get(IFormFile image)
{
//...
return Ok("get");
}
}
Result:
I'm messing with Blazor + SignalR connection. I'd want to Authorize calls to SignalR by using JWT.
Basically I want to attach to SignalR calls the JWT
Here's my Blazor WASM SignalR Code
#page "/"
#using Microsoft.AspNetCore.SignalR.Client
#inject NavigationManager NavigationManager
#implements IDisposable
<div class="form-group">
<label>
User:
<input #bind="userInput" />
</label>
</div>
<div class="form-group">
<label>
Message:
<input #bind="messageInput" size="50" />
</label>
</div>
<button #onclick="Send" disabled="#(!IsConnected)">Send</button>
<hr>
<ul id="messagesList">
#foreach (var message in messages)
{
<li>#message</li>
}
</ul>
#code {
private HubConnection hubConnection;
private List<string> messages = new List<string>();
private string userInput;
private string messageInput;
protected override async Task OnInitializedAsync()
{
hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri("/chathub"))
.Build();
hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{
var encodedMsg = $"{user}: {message}";
messages.Add(encodedMsg);
StateHasChanged();
});
await hubConnection.StartAsync();
}
Task Send() =>
hubConnection.SendAsync("SendMessage", userInput, messageInput);
public bool IsConnected =>
hubConnection.State == HubConnectionState.Connected;
public void Dispose()
{
_ = hubConnection.DisposeAsync();
}
}
But I'm not sure how to attach JWT to this
I've seen this in Js version in section
Bearer token authentication in
this.connection = new signalR.HubConnectionBuilder()
.withUrl("/hubs/chat", { accessTokenFactory: () => this.loginToken })
.build();
https://learn.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-3.1#authenticate-users-connecting-to-a-signalr-hub
What's Blazor's way of doing this?
I tried this:
var token = "eyJhb(...)";
hubConnection = new HubConnectionBuilder()
.WithUrl($"{Configuration["Url"]}/chathub", (HttpConnectionOptions x) =>
{
x.Headers.Add("Authorization", $"Bearer: {token}");
})
.Build();
But it threw error:
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: The format of value 'Bearer: eyJh' is invalid.
System.FormatException: The format of value 'Bearer: eyJhbG' is invalid.
The solution was... to read the docs
var token = "eyJ";
hubConnection = new HubConnectionBuilder()
.WithUrl($"{Configuration["Url"]}/chathub?access_token={token}")
.Build();
Token is provided at connection estabilishing via url
We need to modify startup.cs to support OnMessageReceived
docs url:
https://learn.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-3.1#authenticate-users-connecting-to-a-signalr-hub
services.AddAuthentication(options =>
{
// Identity made Cookie authentication the default.
// However, we want JWT Bearer Auth to be the default.
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
// Configure the Authority to the expected value for your authentication provider
// This ensures the token is appropriately validated
options.Authority = /* TODO: Insert Authority URL here */;
// We have to hook the OnMessageReceived event in order to
// allow the JWT authentication handler to read the access
// token from the query string when a WebSocket or
// Server-Sent Events request comes in.
// Sending the access token in the query string is required due to
// a limitation in Browser APIs. We restrict it to only calls to the
// SignalR hub in this code.
// See https://learn.microsoft.com/aspnet/core/signalr/security#access-token-logging
// for more information about security considerations when using
// the query string to transmit the access token.
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
// If the request is for our hub...
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) &&
(path.StartsWithSegments("/hubs/chat")))
{
// Read the token out of the query string
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
I'm trying to do the following: The response of a webservice is an excel (a separate call for pdf) file. I need to show this file as a link on the aem-page, and whne users click the link, the browser opens (or downloads) the file.
Use case: On the customer page, there is a section with links to Order History (Excel file), Invoice(PDF file), Products catalog(Excel file). Clicking on each link, makes a call to webservice and fetches the respective file.
how to achieve this?
With help from Scott:
http://help-forums.adobe.com/content/adobeforums/en/experience-manager-forum/adobe-experience-manager.topic.html/forum__xhh5-objective_therespo.html
Here's my solution:
From the UI, submit the action to Sling Servlet
<form name="importFileForm" method="get" action="/services/getData">
<input type="submit" title="Submit" value="Submit" name="bttnAction">
</form>
Your Servlet class
public class TTIGetServlet extends SlingAllMethodsServlet {
#Override
protected void doGet(SlingHttpServletRequest request,SlingHttpServletResponse response) throws ServletException,IOException {
...
...
String serviceurl = <<< your webservice url>>>
HttpClient httpclient = HttpClients.custom().build();
generateFile(serviceurl, httpclient, request, response);
RequestDispatcher dispatcher = request.getRequestDispatcher("/content/ttii/en/importfiletest.html");
dispatcher.forward(request, response);
}
}
Generate File method that pops up the file download on browser
public static void generateFile(String serviceurl,
HttpClient httpclient,
SlingHttpServletRequest httpRequest,
SlingHttpServletResponse httpResponse) throws ClientProtocolException, IOException {
HttpResponse response;
HttpGet httpGet = new HttpGet(serviceURL);
// Makes the call to WebService
response = httpclient.execute(httpGet);
// CORE LOGIC
if (response!=null) {
ContentType contentType = ContentType.getOrDefault(response.getEntity());
String mimeType = contentType.getMimeType();
if (mimeType.equals(MIMETYPE_JSON)) {
// Out of context here...
} else {
// SHOW THE FILE
ServletOutputStream sos = httpResponse.getOutputStream();
httpResponse.setContentType("application/vnd.ms-excel");
httpResponse.setHeader("Content-Disposition", "attachment;filename=test.xls");
BufferedHttpEntity buf = new BufferedHttpEntity(response.getEntity());
InputStream istream = buf.getContent();
sos.write(FileHelper.writeFiles(istream));
sos.flush();
}
}
}
I got stuck with an issue in iOS application using PhoneGap framework. I have a web services URL. I need to get JSON response from the web services URL. I had build up some code, but it is not working.
Here is my code:
<div data-role="content" data-theme="a" style="background: Black">
<div data-theme="a">
<span style="font-size: x-large; color: Orange;">Secure Log In</span></div>
<div data-theme="a">
<div data-theme="a">
<input type="password" placeholder="PASSWORD" id="txtPassword" style="background-color: gray;" /></div>
<div data-theme="a" align="right">
<a href="#" data-role="button" onclick="callWebService()" data-corners="false"
data-theme="a" id="clcik" cursor="pointer" style="width: 150px; border-radius: 5px 5px 5px 5px"
data-clickload="show" data-transition="slidefade"><span style="color: Green">Log In</span>
</a>
</div>
function callWebService(){
var query = 'Ocean';
var url = 'http://66.171.142.16/Accountservice/Security/ValidateAccess?accesscode=abcd&type=1';
alert(url);
$.getJSON(url,function(response){
alert('Here!');
});
};
How can I get the JSON response from the url?
I used .Net web Service to access Web Service, Also I have created a Plugin to call .Net web Service. in Java script I used to call web service method as described below.
in script.js
$(".CategoryNavbar").click(function(e){
e.preventDefault();
window.plugins.webservice.GetFlights("service",function(r){printResult(r)},function(e){console.log(e)});
return false;
});
function printResult(fileInfo){
var innerHtmlText=getHtml(fileInfo);
$.mobile.changePage('#CategoryPage',{transition:'slide'});
$('#CategoryPageContent').html(innerHtmlText);
$("#CategoryList").listview();
$("#CategoryList").listview('refresh');
}
function getHtml(fileInfo){
var htmlText='<ul data-role="listview" id="CategoryList" data-theme="c" data-filter="true" data-filter-placeholder="Search">';
for(var index=0;index<fileInfo.Flights.length;index++){
htmlText=htmlText+'<li> '+ fileInfo.Flights[index] +'</li>';
}
htmlText=htmlText+"</ul>";
return htmlText;
}
in Plugin File
/**
* Constructor
*/
function WebService() {
}
/**
* #param methodn The method name for which we want the webService
* #param successCallback The callback which will be called when directory listing is successful
* #param failureCallback The callback which will be called when directory listing encouters an error
*/
WebService.prototype.GetFlights = function(args, successCallback,
failureCallback) {
return cordova.exec(successCallback, failureCallback, 'WebService',
'GetFlights', [ args ]);
};
if (!window.plugins) {
window.plugins = {};
}
if (!window.plugins.webservice) {
window.plugins.webservice = new WebService();
}
Hi Sudheer please check the below code to get the response from web service using Ksoap
public class AndroidWebService extends Activity {
private final String NAMESPACE = "http://www.webserviceX.NET/";
private final String URL = "http://www.webservicex.net/ConvertWeight.asmx";
private final String SOAP_ACTION = "http://www.webserviceX.NET/ConvertWeight";
private final String METHOD_NAME = "ConvertWeight";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
String weight = "3700";
String fromUnit = "Grams";
String toUnit = "Kilograms";
PropertyInfo weightProp =new PropertyInfo();
weightProp.setName("Weight");
weightProp.setValue(weight);
weightProp.setType(double.class);
request.addProperty(weightProp);
PropertyInfo fromProp =new PropertyInfo();
fromProp.setName("FromUnit");
fromProp.setValue(fromUnit);
fromProp.setType(String.class);
request.addProperty(fromProp);
PropertyInfo toProp =new PropertyInfo();
toProp.setName("ToUnit");
toProp.setValue(toUnit);
toProp.setType(String.class);
request.addProperty(toProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
Log.i("myApp", response.toString());
TextView tv = new TextView(this);
tv.setText(weight+" "+fromUnit+" equal "+response.toString()+ " "+toUnit);
setContentView(tv);
} catch (Exception e) {
e.printStackTrace();
}
}
}
And here is an sample code for getting response using JSON in jquery mobile check the code below
$.ajax({
cache: false,
url: wcfServiceUrl + "Authenticate?CompanyID=" + escape(comp) + "&UserName=" + user + "&Password=" + escape(pass) + "&Auth=" + ipaddress+"",
data: "{}",
type: "GET",
contentType: "application/javascript",
dataType: "jsonp",
beforeSend: function (XMLHttpRequest) {
$.mobile.loadingMessageTextVisible = true;
$.mobile.loadingMessage = "Loading Please Wait";
$.mobile.showPageLoadingMsg();
},
complete: function (XMLHttpRequest, textStatus) {
$.mobile.hidePageLoadingMsg();
},
error: function (xmlHttpRequest, status, err) {
$.mobile.loadingMessageTextVisible = true;
$.mobile.loadingMessage = "Web service is not responding. Try again";
$.mobile.showPageLoadingMsg();
var wait = setTimeout(function(){
$.mobile.hidePageLoadingMsg();
},400);
},
error: function () {
jAlert("list failed!",alertmessage);
},
success: function (list) {
var rar = list.split(";");
if(rar[0]=="Error")
{
jAlert(rar[1],alertmessage);
}
else if(rar[0]=="Success")
{
localStorage.setItem( "CompanyID", comp);
localStorage.setItem( "Username", user);
localStorage.setItem( "UserID", rar[1]);
$.mobile.changePage( '#home', { transition: "pop", reverse: false } );
}
else if(rar[0]=="FirstLogin")
{
localStorage.setItem( "CompanyID", comp);
localStorage.setItem( "Username", user);
localStorage.setItem( "UserID", rar[1]);
$.mobile.changePage( '#change-pass', { transition: "slide", reverse: false } );
}
}
});
I am using FB SDK in .net, and on my website there are multiple Facebook emails configured by the user.
Whenever the user wants to post any message on FB, he can pick any email and should be able to login on FB.
The problem is that if the user already logged-in in to FB but wants to post message on some other FB account we are not able to show him the login screen and the message gets posted on the already logged-in account.
Even though we have users auth_type=reauthenticate but this also didn't help to show login screen each time. I need a mechanism like on twitter to force login on FB.
Can anyone please provide help?
A Facebook App – Take note of your App ID and App Secret
Json.NET Installed in your Bin. Download Here: http://json.codeplex.com
The following references need to be added to the page your app will be set up on:
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System.Collections.Generic;
using System.Security.Cryptography;
This is the HTML content:
<div id="fb-root"></div>
function runLogin() {
FB.init({
appId : 'ENTERYOURAPPIDHERE',
status : true,
cookie : true,
xfbml : true,
channelURL: 'ENTERTHEPAGEYOURAPPURLPOINTSTOHERE', // channel.html file
oauth : true
});
<div id="dontLike">
PAGE IS <b>NOT</b> Liked
</div>
</form>
Open up your code-behind for the page. We validated the code signed request.
public bool ValidateSignedRequest()
{
var VALID_SIGNED_REQUEST = Request.Form["signed_request"];
string applicationSecret = "YOURAPPSECRET";
string[] signedRequest = VALID_SIGNED_REQUEST.Split('.');
string expectedSignature = signedRequest[0];
string payload = signedRequest[1];
// Attempt to get same hash
var Hmac = SignWithHmac(UTF8Encoding.UTF8.GetBytes(payload), UTF8Encoding.UTF8.GetBytes(applicationSecret));
var HmacBase64 = ToUrlBase64String(Hmac);
return (HmacBase64 == expectedSignature);
}
private string ToUrlBase64String(byte[] Input)
{
return Convert.ToBase64String(Input).Replace("=", String.Empty)
.Replace('+', '-')
.Replace('/', '_');
}
private byte[] SignWithHmac(byte[] dataToSign, byte[] keyBody)
{
using (var hmacAlgorithm = new HMACSHA256(keyBody))
{
hmacAlgorithm.ComputeHash(dataToSign);
return hmacAlgorithm.Hash;
}
}
public Dictionary<string, string> DecodePayload(string payload)
{
//Remove the bad part of signed_request
//Begin
string[] sB64String = payload.Split('.');
payload = payload.Replace((sB64String[0] + "."), string.Empty);
//End
var encoding = new UTF8Encoding();
var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));
var json = encoding.GetString(base64JsonArray);
var jObject = JObject.Parse(json);
var parameters = new Dictionary<string, string>();
parameters.Add("page", ((bool)jObject["page"]["liked"]).ToString());
parameters.Add("admin", ((bool)jObject["page"]["admin"]).ToString());
return parameters;
}
protected void pageLike()
{
string pageLiked = string.Empty;
var signed_request = Request.Form["signed_request"];
var json = DecodePayload(signed_request);
foreach (KeyValuePair<string, string> objKVP in json)
{
//Note You can also see if a user is an admin by replacing the objKVP.Key with admin
if (objKVP.Key == "page" && objKVP.Value == "True")
{
Response.Redirect("https://www.YOURSITE.com/facebook/app/pageLiked.aspx");
litJson.Text += objKVP.Key + " - " + objKVP.Value + "<br />";
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
pageLike();
}
You can see this example at this link: http://blog.daniellecopp.com/2012/03/19/detect-if-facebook-user-likes-your-page-with-asp-net-2/#comment-52