I am trying to consume a webservice currently made in ajax. I have no idea what this web service is actually doing other than it uses POST Data. When i try to see its output on POSTMAN (Rest api client) I am getting errors.
This is the structure of web service :
var request = {};
request.UserName = "some data"; // this should be always hard coded like this
request.Password = "some data"; // this should be always hard coded like this
request.CurrentUsername = "admin"; // this is hard coded like this for now
request.FirstName = "some data";
request.LastName = "some data";
var send = {};
send.request = request;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "some link",
data: JSON.stringify(send),
dataType: "json",
async: false,
success: function (msg) {
// Process the result here
},
error: function () {
//alert("error");
// Display the error here in the front end
}
});
});
});
I need to get its output in android. Since i have little knowledge in ajax, jquery(backend) and done json parsing(in android) with post method using web service link and parameters. Please guide me how to implement in this case.
Moreover i usually check web service output on postman but here it is giving me bad request every time.
Please help.
have you tried using Fiddler4 by Telerik? i was struggling for 2 weeks at work doing something very similiar to this. I was using webclient to send data from Android to my web page. I got errors non stop. nothing online helped. using fiddler i was able to see what my post data was and where it was and all details. it should help you narrow down a lot of things.
Yes finally got a way to move it. It is very simple and following header is needed in android end thats all
httpPost.setHeader("Content-Type", "application/json");
Related
I have a react-native app that needs to send video/images to my server. I already know that normal posts work but when I attempt to send a formData object, it seems to never leave the phone. Here is my code.
// method = 'POST';
// body = new formData();
// body contains text data and image/video file
const post = (url, body, token, method) => {
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader('Authorization', 'Bearer' + token);
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=---------------------------7692764ac82');
xhr.send(body);
console.log(xhr);
return xhr.response;
}
body is a formData object that contains an image/video. In the object that xhr prints at the console log the _response contains "Binary FormData part needs a content-type header." But it seems I set it correctly right?
Please help, there are other similar questions but I have run out of ideas. I have also tried using fetch with no success.
The error message is not about the content-type header for the request (which you have set), it's about the content-type header for the part (which you did not show, so we have to assume it is missing).
When you add the parts to the FormData, don't forget to include a type. Example for an image:
const body = new FormData();
// ...
body.append('image', {
uri: 'file:///...',
type: 'image/jpeg', // <- Did you miss that one?
name: 'someName',
});
With the type properly set, the React Native runtime should add a content-type header for the part. This is done in FormData.js at line 79 in v0.46.0 (wherein value is the value for your type property):
if (typeof value.type === 'string') {
headers['content-type'] = value.type;
}
So, when type is missing, then content-type header for the part is missing, and then on Android you end up here, where you can see the origin of your error message.
This exact error and root cause is discussed in that GitHub issue.
I have to get JSON from post url.
This is my url
URl: link
Result After process:
{
"success": false,
"error_code": null,
"data": {
"transaction_status": 0
}
}
When I hit this url, mutiple url are calling internally after a long process JSON response will display in WebView. I need to fetch this JSON response by hit this url without showing WebView
Please anybody help me out from this problem.
thanks
Add volley to your project just add the following line.
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
for get json response
private void sendRequest(){
StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json){
// here you can get json.
}
Please follow this tutorial.
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
You need to hit webservice using HttpUrlConnection class of android API and you can get the response in json string format.
http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put
try this this will help
any more query you can ask
This url provided by OP (I mean #dev_mg99) does not consist of a "Server-side" redirect.
The JSON data on the webpage appears after "Javascript" execution.
And as much as I know doing HTTP POST/GET (using any method provided in android) will be useless in this scenario as the server is returning "webpage" and "not JSON data".
(Please correct me if I am wrong. So that I get to learn something new)
The only possible solution coming to my mind is:
1) Load the above url in a WebView
2) Keep on checking whether the WebView has loaded "completely"
3) If it has loaded completely Extract the "html" text of the WebView and obtain the desired JSON text.
No idea how to code (2)... So cannot provide any code.
How I came to know that?
Step 1:
Open above url in (say) google chrome. Wait for sometime and you will see that the page redirects to a webpage with following text:
{"success":false,"error_code":null,"data":{"transaction_status":0}}
which looks like a JSON string.
Step 2: Disable the JavaScript of the browser (For google chrome: Settings -> Show Advanced Settings -> Privacy... Content Settings --> Javascript... Click on "Do not allow any site to run JavaScript"
Step 3: Now, again, try to open above url in the browser... The page will not redirect anywhere.
According to which I conclude that the above url is redirected by JavaScript (Not from Server-Side)
I am trying to upload a file from andriod application, using Jquery to node.js using express..
My client side code is:
function uploadData(win) {
var padI = imagedata.length-1
while( '=' == imagedata[padI] ) {
padI--
}
var padding = imagedata.length - padI - 1
var user = load('user')
$.ajax({
url:'http://'+server+'/lifestream/api/user/'+user.username+'/upload',
type:'POST',
contentType: false,
processdata:false,
data:imagedata,
success:win,
error:function(err){
showalert('Upload','Could not upload picture.')
},
})
}
I have used post form without any content type because if i use multipart/form-data it says error about boundary ..
my server side code using node.js is:
function upload(req,res) {
var picid=uuid()
console.log('Got here..' + __dirname)
//console.log('Image file is here ' + req.files.file.path)
// console.log('local name: ' + req.files.file.name)
var serverPath = __dirname+'/images/' + picid+'.jpg'
fs.rename(
req.files.file.path,
serverPath,
function(error) {
if (error) {
console.log('Error '+error)
res.contentType('text/plain')
res.send(JSON.stringify({error: 'Something went wrong saving to server'}))
return;
}
// delete the /tmp/xxxxxxxxx file created during download
fs.unlink(req.files.file.path, function() { })
res.send(picid)
}
)
}
when the file comes to server, it gives an error of res.files.file is undefined ..
I have searched alot of forums, they say that res.files.file is only access when contenttype is multipart/form-data but then the boundary problem occurs
Any help on that is highly appreciated
Boundary is a special sequence of characters that separates your binary data.
You should submit MIME type as multipart/form-data, as well as set your imagedata to FormData() type (from your snippet it's not clear if it is FormData type).
Here are similar issues and solutions:
How to set a boundary on a multipart/form-data request while using jquery ajax FormData() with multiple files
jQuery AJAX 'multipart/form-data' Not Sending Data?
A great alternative to writing this code is to use filepicker.io This allows you to connect to yoru own s3 bucket. When the file is saved, you get back a callback with the S3 url, you can then simply pass that url to your node api, and save it. I have used this to avoid having to write extra server code for handling file uploads. Extra bonus, if you need to do this with images, and want users to be able to edit the images, you can use Aviary which allows an image to be edited locally, and you then get back another s3 url, that you can then save to your server..
I'm using the Apache Amber libraries to try to retrieve an OAuth2 access token from a Web site under my control. My client code is running under Android.
My code is patterned on the example at:
https://cwiki.apache.org/confluence/display/AMBER/OAuth+2.0+Client+Quickstart
In the first step, I'm able to retrieve a "code" by submitting a GET request using a WebView browser:
OAuthClientRequest request = OAuthClientRequest
.authorizationLocation(AUTHORIZE_URL)
.setClientId(CLIENT_ID)
.setRedirectURI(REDIR_URL)
.setResponseType(CODE_RESPONSE)
.buildQueryMessage();
webview.loadUrl(request.getLocationUri());
I use a WebViewClient callback to capture the redirect URL with the "code" parameter. So far, so good.
Using that code, I try to retrieve my access token:
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthClientRequest request = OAuthClientRequest
.tokenLocation(ACCESS_TOKEN_URL)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setRedirectURI(REDIR_URL)
.setCode(code)
.buildBodyMessage();
GitHubTokenResponse oAuthResponse =
oAuthClient.accessToken(request, GitHubTokenResponse.class);
Each time I run my code, I get an OAuthProblemException, where the message is that I have an invalid request due to a missing parameter, access_token.
Another StackOverflow post mentions this exception from a similar OAuth2 request, which in that case was caused by having different redirect URIs across OAuth requests. But I've made sure my redirect URIs are the same by using a named constant. Here's the link to that post:
OAuthProblem, missing parameter access_token
Now, I can print out the code returned by the first request, and paste it into a curl command run from my desktop machine:
curl -d "code=...&client_id=...&client_secret=...&grant_type=...&redirect_uri=..." http://my_website.com
and I get a nice JSON response from my site with an access_token.
Why does the call from Java fail, where my hand-rolled command line succeeds?
I had the same problem implementing the client and the server, the problem is about one mistake in the Client Example in the Apache Amber (Oltu) project:
First you have the Auth code request (which work):
OAuthClientRequest request = OAuthClientRequest
.authorizationLocation(AUTHORIZE_URL)
.setClientId(CLIENT_ID)
.setRedirectURI(REDIR_URL)
.setResponseType(CODE_RESPONSE)
.**buildQueryMessage**();
And second the request about the Access Token (which don't work):
OAuthClientRequest request = OAuthClientRequest
.tokenLocation(ACCESS_TOKEN_URL)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setRedirectURI(REDIR_URL)
.setCode(code)
.**buildBodyMessage**();
The mistake is about the buildBodyMessage() in the second request. Change it by buildQueryMessage().
Solved in my case.
Amber/Oltu "Missing parameter access_token" error may mean that GitHubTokenResponse or OAuthJSONAccessTokenResponse are unabled to translate response body for any reason. In my case (with Google+ oAuth2 authentication), the response body, is not parsed properly to the inner parameters map.
For example:
GitHubTokenResponse
parameters = OAuthUtils.decodeForm(body);
Parse a form-urlencoded result body
... and OAuthJSONAccessTokenResponse has the next parse function
parameters = JSONUtils.parseJSON(body);
This JSONUtils.parseJSON is a custom JSON parser that not allow for me JSON response body from GOOGLE+ and throws an JSONError (console not logged),
Each error throwed parsing this parameters, are not console visible, and then always is throwed doomed "Missing parameter: access_token" or another "missing parameter" error.
If you write your Custom OAuthAccessTokenResponse, you can see response body, and write a parser that works with your response.
This is what I encountered and what I did to get it working:
I quickly put together a similar example described in:
https://cwiki.apache.org/confluence/display/OLTU/OAuth+2.0+Client+Quickstart
and:
svn.apache.org/repos/asf/oltu/trunk/oauth-2.0/client/src/test/java/org/apache/oltu/oauth2/client/OAuthClientTest.java
This was my command to execute it:
java -cp .:./org.apache.oltu.oauth2.client-1.0.1-20150221.171248-36.jar OAuthClientTest
I also ended up with the above mentioned error where the access_token was expected. I ended up debugging in intellij and traced an anomaly with the if condition which checks that the string begins with the "{" character.
In doing so, I also added the following jar to my classpath so that I may debug the trace a little deeper.
./java-json.jar
(downloaded from http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm)
During the next debug session, the code actually started working. My mate and I eventually found the root cause was due to the JSON jar not being included.
This is the command which works:
java -cp .:./java-json.jar:./org.apache.oltu.oauth2.client-1.0.1-20150221.171248-36.jar OAuthClientTest
I was having the same problem when trying to get the access token from fitbit OAuth2. buildBodyMessage() and buildQueryMessage() were both giving me missing parameter, access_token.
I believe this is something to do with the apache oauth2 client library. I ended up making simple post requests using spring's RestTemplate and it's working fine.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.set("Authorization", "Basic " + "MjI5TkRZOjAwNDBhNDBkMjRmZTA0OTJhNTE5NzU5NmQ1N2ZmZGEw");
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("client_id", FITBIT_CLIENT_ID);
map.add("grant_type", "authorization_code");
map.add("redirect_uri", Constants.RESTFUL_PATH + "/fitbit/fitbitredirect");
map.add("code", code);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(FITBIT_TOKEN_URI, request, String.class);
log.debug("response.body: " + response.getBody());
I have system that send data in json format from ASP.NET MVC to android system.
I try sample from this site to achieve transfer data. When I try to call site to return result, there always return result without tag HTML in web browser but it work and display in web browser. In first time, I try in JQuery to display the result, but always say there no data. After that I test it Android system, but result always return "{}" that mean no data there. Then I found there problem, about result Json from ASP.NET. Because I'm curious about this problem, I try sample JSON from this site, then it work in android.
My question why this could be happen and I could be resolve?
Sample Json work from site:
{"query":"Bo","suggestions":["Bognor
Regis","Bolton","Bournemouth","Camborne","Eastbourne","Loughborough",
"Peterborough","Scarborough","University of Bolton","Boston
University","Bournemouth University","Camborne School of Mines",
"Loughborough University","Ravensbourne College of Design and
Communication","University of Hull (Scarborough Campus)"]}
Sample Json Doesn't Work retrieve from ASP.NET MVC using JsonResult:
[{"Name":"Saab","Color":"Red"},{"Name":"Volvo","Color":"Blue"}]
Your question is not very clear but as far as I understand it you have an ASP.NET MVC site that is consumed by an Android client and you want this site to send JSON formatted data. If this is the case you could return a JsonResult from your controller action:
public ActionResult SomeAction()
{
// The data could be any class you would like to serialize
var data = new
{
query = "Boo",
suggestions = new[]
{
"Bognor Regis", "Bolton"
}
};
return Json(data, JsonRequestBehavior.AllowGet);
}