I have to pass UserName and password as arguments into GET method for validation.after processing I need to get response.so how can I pass value into RESTful webservice GET method?
To pass parameters in HTTP GET you should use a ? delimiter. Such as
https://mywebsite.com/user/login?username=bob&password=123
https://mywebsite.com/user/login?paramname1=value1¶mname2=value2
Make sure to always use https with any sensitive data. You may also need to escape/encode both username and password to allow extended ASCII. If you need to support UNICODE you should consider using a POST request.
I think, you should use POST method if you want to do something with user name and password. because when you use GET method, the password would be visible on the URI,
https://samplesite.com/page/login?username=John&password=123
https://sampleste.com/page/login?name1=value1&name2=value2
Instead, you could use POST method to send user name and password values and in that case the URI would like below
https://samplesite.com/page/login
And the values will be sent as,
POST /page/login.asp HTTP/1.1
Host: samplesite.com
name1=value1&name2=value2
And you get below advantages on POST Method for secured transaction with server.
It never cached
Requests will remain in the browser history
Requests cannot be bookmarked
Requests have no restrictions on data length
You can do the following for Login validation,
// Create a new HttpClient and Post Header
String downloadedString= null;
HttpClient httpclient = new DefaultHttpClient();
//for registerhttps://te
HttpPost httppost = new HttpPost("YOUR LOGIN URL");
//add data
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", UserName_Edit.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password", userPassword_Edit.getText().toString()));
//add data
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStream in = response.getEntity().getContent();
StringBuilder stringbuilder = new StringBuilder();
BufferedReader bfrd = new BufferedReader(new InputStreamReader(in),1024);
String line;
while((line = bfrd.readLine()) != null)
stringbuilder.append(line);
downloadedString = stringbuilder.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("downloadedString:in login:::"+downloadedString);
Use AsyncTask for your authentication and write the above method in the doInBackground().
EDIT
You can follow below tutorials also,
http://sarangasl.blogspot.in/2011/06/android-login-screen-using-httpclient.html
http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/
Hope it helps.
Hi you can pass arguments to GET method in RESTfull like :
http://yoururl/<arg1>/<arg2>
eg.
http://yoururl/abc/123
Related
I am trying to implement the MOT history API https://dvsa.github.io/mot-history-api-documentation/ and they give an example using CURL which works with the supplied api key successfully when using an online CURL tool.
I am trying to implement this in Android and realise I have to use something like HttpPost rather than CURL, this is my code:
//Tried with full URL and by adding the registration as a header.
//HttpPost httpPost = new HttpPost("https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests?registration=" + reg_selected);
HttpPost httpPost = new HttpPost("https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests");
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Accept", "application/json+v6");
httpPost.addHeader("x-api-key", "abcdefgh123456");
httpPost.addHeader("registration", reg_selected);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
InputStream inputStream = response.getEntity().getContent();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String readLine = bufferedReader.readLine();
String jsonStr = readLine;
JSONObject myJsonObj = new JSONObject(jsonStr);
}else if (response.getStatusLine().getStatusCode() == 400){
//Bad Request Invalid data in the request. Check your URL and parameters
error_text = "Bad Request";
}else if (response.getStatusLine().getStatusCode() == 403){
//Unauthorised – The x-api-key is missing or invalid in the header
error_text = "Authentication error"; //<<<< FAILS HERE 403
}
response.getStatusLine().getStatusCode() returns • "403 – Unauthorised – The x-api-key is missing or invalid in the header".
However the x-api-key that I use works correctly with the online CURL test so the actual key is correct but how I am adding it to my android code request must be invalid or similar.
Can anyone throw any light as to the correct way to convert the CURL into Android java so that the server does not return 403?
Thanks
It's easy to do with Jsoup:
// CREATE CONNECTION
Connection conn=Jsoup.connect("URL_GOES_HERE");
// ADD POST/FORM DATA
conn.data("KEY", "VALUE");
// ADD HEADERS HERE
conn.header("KEY", "VALUE");
// SET METHOD AS POST
conn.method(Connection.Method.POST);
// ACCEPT RESPONDING CONTENT TYPE
conn.ignoreContentType(true);
try
{
// GET RESPONSE
String response = conn.execute().body();
// USE RESPONSE HERE
// CREATE JSON OBJECT OR ANYTHING...
} catch(HttpStatusException e)
{
int status = e.getStatusCode();
// HANDLE HTTP ERROR HERE
} catch (IOException e)
{
// HANDLE IO ERRORS HERE
}
Ps: I guess you are confused with Header and Post Data. The key etc (Credentials) must be used as Post Data and Content Type etc as Header.
I consulted the API documentation and sent it successfully in api explorer-> Envelopes: create. I also got json & request path & token. I used httpclient post in java and received Object moved Object moved to here . Does anyone know what I missed?
`
DocsignDocument docsignDocument = new DocsignDocument();
docsignDocument.setDocumentBase64
docsignDocument.setDocumentId("1");
docsignDocument.setFileExtension("pdf");
docsignDocument.setName("Test.pdf");
list.add(docsignDocument);
Recipients recipients = new Recipients();
Signers signers = new Signers();
signers.setEmail("xxxx");
signers.setName("Qin");
signers.setRecipientId("1");
Signers signers1 = new Signers();
signers1.setEmail("xxx#qq.com");
signers1.setName("OYX");
signers1.setRecipientId("2");
List<Signers> signersList = new ArrayList<>();
signersList.add(signers);
signersList.add(signers1);
recipients.setSigners(signersList);
dataJson.put("documents",list);
dataJson.put("emailSubject","TEST");
dataJson.put("recipients",recipients);
dataJson.put("status","sent");
String data = dataJson.toJSONString();
String results2 = HttpDocusignUtils.httpPostJson("https://account-d.docusign.com/restapi/v2.1/accounts/xxx/envelopes",access_token,data)`
post request:
public static String httpPostJson(String uri, String token, String obj) {
String result = "";
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Content-Type", "application/json"); // 添加请求头
httpPost.addHeader("Authorization","Bearer "+token);
httpPost.addHeader("Accept-Encoding","gzip,deflate,sdch");
httpPost.setEntity(new StringEntity(obj));
System.out.println(httpPost);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instreams = entity.getContent();
result = convertStreamToString(instreams);
System.out.println(result);
}
} catch (Exception e) {
e.getMessage();
}
return result;
}
https://account-d.docusign.com/restapi/v2.1/accounts/xxx/envelopes is not a valid DocuSign endpoint.
The Account Server (account-d.docusign.com) is used to get a token and make a UserInfo call to determine the correct base URL for a particular account.
Because you're in the Demo environment, your base url will begin with https://demo.docusign.net
Well, one issue is that the the Document model in Java is Document from
import com.docusign.esign.model.Document;
To debug, I suggest using the DocuSign API logging feature. Then update (edit) your question to include the JSON shown in the log.
Were you able to run the code examples for Java? See eg-03-java-auth-code-grant
Also, please tell us (by editing your question) what you are trying to do.
Creates envelopes - Use Base Url in Api Call
https://demo.docusign.net/restapi/v2.1/accounts/
Error Reason is use Wrong url - https://account-d.docusign.com/restapi/v2.1/accounts/
DocuSign Developers Documentation
I'm trying to login into a website using java and jsoup. But every time I execute my post request I get an IOExeption. The website is www.seriecanal.com. I would appreciate it if someone could review the html form and tell me if I am creating the name-value pairs correctly and if there are any other obvious mistakes with the login. Here's my code:
public HttpResponse postData()
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://seriecanal.com/index.php?page=member");
try
{
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//Get value of input "Regresa_web" because it changes each time i access the site
String Codigo_Fuente ="";
URL url = new URL("http://seriecanal.com/");
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = rd.readLine()) != null)
{
Codigo_Fuente= Codigo_Fuente+line;
}
Document Doc = Jsoup.parse(Codigo_Fuente);
Element Regresa_WEb = Doc.getElementById("regresa_web");
String Valor_Regresa_Web = Regresa_WEb.attr("value");
//create name value pairs of the form
nameValuePairs.add(new BasicNameValuePair("_UserName", "userontheweb"));
nameValuePairs.add(new BasicNameValuePair("_Pwd", "123456789"));
nameValuePairs.add(new BasicNameValuePair("btnLogin", "Ingresar"));
nameValuePairs.add(new BasicNameValuePair("_submit_check", "1"));
nameValuePairs.add(new BasicNameValuePair("remember", "ON"));
nameValuePairs.add(new BasicNameValuePair("regresa_web", Valor_Regresa_Web));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse Response = httpclient.execute(httppost);
return Response;
}
catch (ClientProtocolException e)
{
return null;
}
catch (IOException e)
{
Log.i("ERROR", e.toString());
e.printStackTrace();
return null;
}
}
Stack:
04-21 13:42:04.206: D/dalvikvm(324): GC freed 15163 objects / 721152 bytes in 153ms
04-21 13:42:08.026: I/Resources(324): Loaded time zone names for en_US in 1863ms.
04-21 13:42:23.816: I/global(324): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.
04-21 13:42:25.696: D/dalvikvm(324): GC freed 21866 objects / 1346160 bytes in 168ms
If you use fiddler or firebug you can interrogate the actual parameters that get sent. When I did this this is what I saw
_submit_check=1
btnLogin=Ingresar
password=test
remember=ON
username=test
It looks like you are sending the wrong params. The form input names do seem different to the ones being sent e.g. _UserName, but you never know if javascript is bound to the event and there is some additional magic going on there. As a result i always use firebug/fiddler.
Here is Java code that POSTs data to a website and than gets redirected as a response (status 302). It works perfectly on my PC (Eclipse, Java, Ubuntu), it does exactly what I want it to do.
I tried quite everything to post the code functionality but I just am not able to.
Java code:
// Preparing the CLIENT and POST Method
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://na.leagueoflegends.com/ladders/solo-5x5");
try {
// Add your POST METHOD attributes
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("op", "Search"));
nameValuePairs.add(new BasicNameValuePair("player", "Jaiybe"));
nameValuePairs.add(new BasicNameValuePair("ladder_id", "3"));
nameValuePairs.add(new BasicNameValuePair("form_build_id",
"form-526370b788622996caa3669e7b975ccf"));
nameValuePairs.add(new BasicNameValuePair("form_id",
"ladders_filter_form"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
// RESPONE THAT WORKS WITH JAVA
System.out.println("Location:");
String LocationHeader = response.getFirstHeader("location").getValue();
System.out.println(LocationHeader);
System.out.println();
// To get the BODY I would have to parse that again - since its not REDIRECTING automatically
HttpClient httpclient2 = new DefaultHttpClient();
HttpPost httppost2 = new HttpPost(LocationHeader);
response = httpclient2.execute(httppost2);
System.out.println("And EVEN the response body:");
System.out.println(EntityUtils.toString(response.getEntity()));
Code does:
Posts
Gets Redirected - gets header of Location
Parses the Location
And I need android to do the same. Either "Location" or body of repsonse, is ok, I dont need both.
The post: http://www.anddev.org/networking-database-problems-f29/httppost-clientprotocolexception-t56118.html
I have found the problem!
httpclient.getParams().setParameter("http.protocol.version",
HttpVersion.HTTP_1_0);
Just changing this one line - version 1_0 works and 1_1 does not. Don't ask me why :)
Thank you all!
Please try the following code. The location in the header is missing, because the page has already redirected. So we can disable redirection to get the location tag.
httpclient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
Try calling this after you create your http client so that it follows your redirect
httpclient.getParams().setParameter("http.protocol.allow-circular-redirects", true);
I'm trying out the twitter streaming api. I could succesfully filter tweets by using curl, as stated here:
curl -d #tracking http://stream.twitter.com/1/statuses/filter.json -u <user>:<pass>
where tracking is a plain file with the content:
track=Berlin
Now I tried to do the same thing in JavaSE, using Apache's HTTPComponents:
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(<user>, <pass>);
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
HttpPost httpPost = new HttpPost("http://stream.twitter.com/1/statuses/filter.json");
HttpParams params = new BasicHttpParams();
params = params.setParameter("track", "Berlin");
httpPost.setParams(params);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String t;
BufferedReader br = new BufferedReader(new InputStreamReader(instream));
while(true) {
t = br.readLine();
if(t != null) {
linkedQueue.offer(t);
}
}
}
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
finally{
httpClient.getConnectionManager().shutdown();
}
When I run that, I get:
No filter parameters found. Expect at least one parameter: follow track
as a single entry in my linkedQueue. Seems the api wants the parameter in a different form, but cannot find any hint in the documentation. Can somebody share some experiences with the api or see any other problem with the code? Thanks!
EDIT
Putting the filter parameter into the params was a bad idea. As it's post data, it needs to be defined as an Entity before the request is being made:
StringEntity postEntity = new StringEntity("track=Berlin", "UTF-8");
postEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(postEntity);
That's what I was doing wrong. Thanks Brian!
I suspect you need to post the data as the contents of your HTTP post. The man page for curl -d says:
(HTTP) Sends the specified data in a
POST request to the HTTP server, in
the same way that a browser does when
a user has filled in an HTML form and
presses the submit button. This will
cause curl to pass the data to the
server using the content-type
application/x-www-form-urlencoded.
so I believe you have to set that content type and put the contents of the tracking file in the body of your post.