Could you please comment what wrong with this client side restlet code.
It is necessary:
Add HTTP header X-MF-Auth-Token with value token
Place JSON file to the body of HTTP request
Make POST request to server
Post request generates "400" error. Thank you very much!
ClientResource cr = new ClientResource(servername + "/json/place");
cr.getRequest().getAttributes().put("X-MF-Auth-Token", token);
Form form = new Form ();
form.add("Category", "");
form.add("CategoryId", "A1EECAB9-3E66-4F14-92E9-465EDFB22BA7");
form.add("Latitude", "0");
form.add("Longitude", "0");
form.add("Name", "Loremipsum");
form.add("PlaceId", "00000000-0000-0000-0000-000000000099");
cr.post(form, MediaType.APPLICATION_JSON);
if (cr.getStatus().isSuccess()) {
// Register Successful
Log.v("Register()", "Successeful");
return true;
} else {
Log.v("Register()", "ERROR");
return false;
}
} catch (ResourceException e) {
// Login Error
Log.v("AddPlace() error:", e.getStatus().toString());
return false;
}
You can use JSONObject instead of Form:
JSONObject jo = new JSONObject();
try {
jo.add("Category", "");
jo.add("CategoryId", "A1EECAB9-3E66-4F14-92E9-465EDFB22BA7");
jo.add("Latitude", "0");
jo.add("Longitude", "0");
jo.add("Name", "Loremipsum");
jo.add("PlaceId", "00000000-0000-0000-0000-000000000099");
} catch (JSONException ex) {
}
cr.post(new JsonRepresentation(jo), MediaType.APPLICATION_JSON);
i think you're not adding X-MF-Auth-Token to the header.
try
Form headers = (Form) cr.getRequest().getAttributes("org.restlet.http.headers");
if (headers == null) {
headers = new Form();
cr.getRequest().getAttributes.put("org.restlet.http.headers", headers);
}
headers.add("X-MF-Auth-Token", token);
Related
I have a strange issue with my HttpRequest, i have 2 application one is clientside and the other one is RESTAPI, the issue is i am trying to update my entity by sending a request which the content is Json
public async Task<bool> Update(string url, T obj, string id)
{
var request = new HttpRequestMessage(HttpMethod.Put, url+id);
if (obj == null || String.IsNullOrEmpty(id))
{
return false;
}
request.Content = new StringContent(JsonConvert.SerializeObject(obj),
Encoding.UTF8, "application/json");
var client = _client.CreateClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("bearer", GetBearerToken());
HttpResponseMessage response = await client.SendAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.NoContent)
{
return true;
}
return false;
}
And here is my clientapp controller below;
[HttpPost]
public async Task<IActionResult> EditUser([FromForm] UserDTO userDTO ,string id)
{
if (!ModelState.IsValid)
{
return RedirectToAction("ErrorPage", "Error");
}
userDTO.Id = id;
await _userRepository.Update(EndPoints.UserEndPoint,userDTO,id);
return RedirectToAction("GetUsers");
}
and i dont know if it is necessary because it doesnt hit even the breakpoint but i am also showing my RESTAPI code below;
/// <summary>
/// Update user
/// </summary>
/// <param name="id"></param>
/// <param name="userDTO"></param>
/// <returns></returns>
[HttpPut("{id}")]
[Authorize(Roles = "Administrator")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> UpdateUser(string id, [FromBody] UserDTO userDTO)
{
var location = GetControllerActionNames();
try
{
_logger.LogInfo($"{location}: Requested an Update for id: {id} ");
if (string.IsNullOrEmpty(id) || userDTO == null || id != userDTO.Id)
{
_logger.LogError($"{location}: Request for Id: {id} is not sucessful");
return BadRequest();
}
if (!ModelState.IsValid)
{
_logger.LogWarn($"{location}: Data was incomplete!");
return BadRequest(ModelState);
}
var isExist = await _userRepo.IsExist(id);
if (!isExist)
{
_logger.LogWarn($"{location}: with Id: {id} is not exisist");
return NotFound();
}
var usermap = _mapper.Map<CompanyUser>(userDTO);
if (usermap == null)
{
_logger.LogWarn($"{location}: Data is empty");
return BadRequest();
}
var response = await _userRepo.Update(usermap);
if (!response)
{
_logger.LogError($"{location}: Update is failed ");
return NotFound();
}
_logger.LogInfo($"User is Updated");
return NoContent();
}
catch (Exception e)
{
return InternalError($"{location} - {e.Message} - {e.InnerException}");
}
}
RESTAPI code is working when i try with PostMan.
But from the client side where i send the request it sometimes works but usually gives bad request as response instanly i mean not even go to my RESTAPI. Can you help to resolve this strange problem.
I fixed the issue, on my API Login
Because i was using Microsoft Identity and when i use await PasswordEmailSignInAsync(userName, password, false, false); it automatically genereates application cookie on my API side and i used fiddler to capture requests and i saw there when i get an error or on my API side when the thread exits the application cookie also expires after that when i made a new request from my Client to My API it was giving the bad request on my client side instantly.
So i changed my signin method to var user = await _userManager.FindByEmailAsync(userDTO.Email); var result = await _userManager.CheckPasswordAsync(user, userDTO.Password);
in order to avoid from the application cookie creation. I had already JWT token structure in my application but was useless because default authorized attribute was not using bearer schema and i modified my startup.cs a little help from [Authorize Attribute not working with JWT Access Token in ASP.Net Core1
and now everything works without any problem!.
[Route("login")]
[HttpPost]
[AllowAnonymous]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Login([FromBody] UserLoginDTO userDTO)
{
var location = GetControllerActionNames();
try
{
var userName = userDTO.Email;
var password = userDTO.Password;
_logger.LogInfo($"{location}: User:{userName} - Attempted to Login");
//var result = await PasswordEmailSignInAsync(userName, password, false, false);
var user = await _userManager.FindByEmailAsync(userDTO.Email);
var result = await _userManager.CheckPasswordAsync(user, userDTO.Password);
if (result)
{
_logger.LogInfo($"{location}: User:{userName} Logged in Succesfully");
var tokenstring = await GenerateJSONWebToken(user);
return Ok(new { token = tokenstring });
}
_logger.LogWarn($"{location}: User:{userName} couldnt logged in ");
return Unauthorized(userDTO);
}
catch (Exception e)
{
return InternalError($"{location} - {e.Message} - {e.InnerException}");
}
}
I am facing one problem with android accessing ATG sessionconfirmationNumber using rest API, I am using http urlconnection to achive the same, Code is working perfectly and I am getting output also, but the result in the Json response is rounded as the number is large. below are the code.
try {
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Defined URL where to send data
// URL url = new URL("http://10.201.62.27:8080/Test-Servlet/TestServletAndroid?"+data);
URL url = new URL("http://52.70.41.98:7203/rest/model/atg/rest/SessionConfirmationActor/getSessionConfirmationNumber");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
HttpURLConnection httpConnection = (HttpURLConnection) conn;
Log.e("Connection", conn.toString());
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Content-Type", "text/plain");
httpConnection.connect();
// Get the server response
reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
response = sb.toString();
Log.v("ResponseVALID", response);
JSONObject json = new JSONObject(response);
Log.v("Tag0", json.toString());
scn = json.getLong("sessionConfirmationNumber");
/*String srr[] = response.split(":");
for(int i =0;i<srr.length;i++){
Log.v("TAG2:",srr[i]);
}
SCN=srr[1].replace("}", "");
SCN= SCN.trim();
Log.v("SCN ",SCN);
scn=Long.parseLong(SCN);*/
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
I have faced the same problem with angularjs on the web-portal, XMLHttp request helped me out to achieve the goal.
Can I use XMLHttp request from android studio?, if yes!, Please give me some reference as I have tried and nothing got worked out for me.
Any help would be appreciated.
I believe the line:
httpConnection.setRequestProperty("Content-Type", "text/plain");
need to be:
httpConnection.setRequestProperty("Content-Type", "application/json");
Hello I have been using Spring 3 for my project, I have been stuck in on point.
if(ajax){
User user = userTemplate.getUser(form.getCreator_id());
int isPremium = user.getPremium();
if ( isPremium == 1 ){
Map<String,String> resultMap = new HashMap<String,String>();
response.setHeader("Access-Control-Allow-Headers", "*");
response.addHeader("Access-Control-Allow-Origin", "*");
resultMap.put("result", "success");
return new Gson().toJson(resultMap);
}else{
return "redirect:/f/redirectedUrl?url="+form.getWeb_page();
}
}
redirectedUrl controller is just for redirecting, but if the request is ajax request then i want to response the request as json.
How can I achieve this, thanks.
Edit : I can understand if request is ajax or not. My problem is if it is ajax i want to response json, if it is not then i want to redirect.
Use this code in your controller to identify if request is ajax or not and based on that you can add your logic.
boolean ajax = "XMLHttpRequest".equals(
getRequest().getHeader("X-Requested-With"));
You can decide it from header("X-Requested-With") of your httpRequest object.
public ModelAndView getDetails(HttpServletRequest request, HttpServletRespone response) {
if(ajax) {
try {
new MappingJacksonHttpMessageConverter().write(object, MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
} catch(Exception e) {
logger.error("Error when converting to json");
}
return null;
} else {
return new ModelAndView("viewName");
}
}
I'm attempting to ping my archiva server, which isn't a problem on pages not requiring authorization. However, when I try to pingWithAutz, I cannot help but get a 403 error. Here is the relevant code snippet:
public FormValidation doTestConnection(#QueryParameter("url") String url,
#QueryParameter("username") String usr,
#QueryParameter("password") String pwd)
throws Exception {
if (url == null || url.equals("")) {
return FormValidation.error("Please, set a correct url");
}
url = url.endsWith("/") ? url.substring(0, url.length() - 1) : url;
HttpPost post = new HttpPost(url + "/restServices/redbackServices/loginService/pingWithAutz");
String authzHeader = "Basic " + Base64Utility.encode(( usr + ":" + pwd ).getBytes());
post.setHeader("Authorization",authzHeader);
HttpClientBuilder builder = HttpClientBuilder.create();
CloseableHttpClient httpclient = builder.build();
CloseableHttpResponse response = null;
try {
response = httpclient.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
return FormValidation.error("Cannot connect to the server. Response Code : " +
response.getStatusLine());
}
} catch(Exception e){
System.out.println(e);
}
finally {
response.close();
}
return FormValidation.ok("Successfully connected to Archiva Server.");
}
What am I doing wrong that it won't authenticate properly?
You should try with a HttpGet as this service is expected a GET http and not a POST.
See http://archiva.apache.org/docs/2.2.0/rest-docs-redback-rest-api/resource_LoginService.html#path__loginService_ping.html
HTH
I have the following code. The async call never returns anything. Even for google.com.
try
{
using (
var client = new HttpClient()) {
var response = client.GetAsync("http://www.google.com");
Debug.WriteLine("Coming here1"+response.Result.IsSuccessStatusCode);
if (response.Result.IsSuccessStatusCode)
{
// by calling .Result you are performing a synchronous call
Debug.WriteLine("Coming here1");
var responseContent = response.Result.Content;
// by calling .Result you are synchronously reading the result
string responseString = responseContent.ReadAsStringAsync().Result;
//Console.WriteLine(responseString);
}
else { Debug.WriteLine("else"); }
}
}
catch(Exception e)
{
Debug.WriteLine(e.ToString());
}
}
Try This
try{
WebClient wc = new WebClient();
wc.DownloadStringCompleted+= (sender,args) => {
Debug.WriteLine(args.results);
};
wc.DownloadStringAsync(new Uri(#"http://www.Google.com",UriKind.RelativeOrAbsolute));
}
catch(Exception e){ Debug.WriteLine(e.Message); }
You don't appear to be awaiting your Async call.
Try changing var response = client.GetAsync("http://www.google.com"); to var response = await client.GetAsync("http://www.google.com");
Remember to mark your method as async.
you're also blocking on your async call ReadAsStringAsync().Result. As with client.GetAsync, make sure to await the call instead of blocking with Result. This blog post speaks a bit on the topic.
Read up a bit on async/await. You'll love it once you get the hang of it.