I am trying to implement a class that gets data from mysql via my web service. I have previously used a http post to get information from a table but this time I intend a user to input a string into an editText, press search and the textview to display the query.For example, Imagine there are two columns of the mysql table: Firstname and surname; I would like to be able to get the surname by searching the Firstname (Entering the Firstname into the EditText and displaying the surname of that person).I have developed the PHP script but is it possible to use the HTTP get method based on an input string? how? I've only seen tutorials directing straight to the php link
This is a example how you could do it by using NameValuePairs which you can pass to the php file using a post request.
private void sendData(ArrayList<NameValuePair> data)
{
// 1) Connect via HTTP. 2) Encode data. 3) Send data.
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://www.blah.com/AddAccelerationData.php");
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = httpclient.execute(httppost);
Log.i("postData", response.getStatusLine().toString());
//Could do something better with response.
}
catch(Exception e)
{
Log.e("log_tag", "Error: "+e.toString());
}
}
Now lets say you want to use this method to pass info(i.e. your parameter to the php file.
//Add data to be send.
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("parameter",editTextValue));
this.sendData(nameValuePairs);
Now on the php side of things you can then get this parameter value by calling:
//Retrieve the data.
$parameter = $_POST['parameter'];
//Now call on your query or function or w/e it is using this parameter.
To use GET, simply encode the values into your URL, e.g.
String url = "http://myserver.net/script.php?first=" + URLEncoder.encode(first) +
"&last=" + URLEncoder.encode(last);
And then use an HttpGet object with your HttpClient:
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(new HttpGet(url));
Processing the response is then the same as if you had posted it.
Related
I'm working with the Sinusbot API making post Requests in Java.
I make the most and get a response of 200, which is good.
However, It's also suppose to return a token for login when making the request, but I can't figure out how to get it.
Any ideas?
https://www.sinusbot.com/api/#api-General-login
Within a try catch statement
HttpPost request = new HttpPost("http://127.0.0.1:8087/api/v1/bot/login");
// StringEntity params =new StringEntity("{'username': 'xx','password': 'foobar', 'botId': 'fillme'}");
String payload = "{'username': 'test','password': 'atisbot', 'botId': '2ad5bffa-4374-4ef4-abae-77e793163577'}"; //atisbot 172b398f-f217-4bbc-8e14-9ea5f1463db7
StringEntity entity = new StringEntity(payload,
ContentType.APPLICATION_FORM_URLENCODED);
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
System.out.println(response.getStatusLine().getStatusCode());
Response is plain text and it probably is the token.
String token = EntityUtils.toString(response.getEntity())
I am creating a 3rd party java application (desktop) that needs to connect to a php-based site and log in to gather pertinent data. There is no accessible web service, no API, and every user will have their own secure login. The site uses dojo (if that matters), and I am using Java HttpClient to send the post.
HttpPost httppost = new HttpPost("https://thewebsite.net/index/login"); // .php ?
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
//initialize the response string
String nextpage = "";
try {
// Add nvps
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("", ""));
nameValuePairs.add(new BasicNameValuePair("login", "USER"));
nameValuePairs.add(new BasicNameValuePair("", ""));
nameValuePairs.add(new BasicNameValuePair("pass", "PASSWORD"));
nameValuePairs.add(new BasicNameValuePair("Submit", ""));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
userID = EntityUtils.toString(response.getEntity());
System.out.println(nextpage);
httppost.releaseConnection();
}
...
Now, the issue I'm having is that the response given to me is a validation jscript for the user / pass fields through dojo.
<script type='text/javascript'>
dojo.require("dojox.validate._base");
function validate_RepeatPassword(val, constraints)
{
var isValid = false;
if(constraints) {
var otherInput = dijit.byId(constraints[0]);
if(otherInput) {
var otherValue = otherInput.value;
isValid = (val == otherValue);
}
}
return isValid;
}
</script>
I simply want to connect, parse an html response, and close the connection.
When I use firebug, I get this as the post method, but I can't seem to get it to run:
Referer https://thewebsite.net/index/login
Source login=USER&pass=PASSWORD
When I use the HttpPost client to construct a direct post url without namevaluepairs:
HttpPost httppost = new HttpPost("https://thewebsite.net/index/login?login=USER&pass=PASSWORD");
, I get an error response that states "the user and pass fields cannot be left blank."
My question is: Is there a direct method to log in that is simpler that I'm missing that will allow me to successfully continue past log in?
Thanks - I love the SO community; hope you can help.
I think best library for doing this is jsoup
Connection.Response res =
Jsoup.connect("https://thewebsite.net/index/login?login=USER&pass=PASSWORD")
.method(Method.POST)
.execute();
After this you need to make verification also. You need to read cookies, request parameters and header parameters and this will work.
I didn't end up using your exact code (with the post parameters), but JSoup was the fix.
here's what I used:
`res = Jsoup.connect("https://thewebsite.net/index/login")
.data("login", User).data("pass", Pass)
.userAgent("Chrome").method(Method.POST).execute();
//then I grabbed the cookie and sent the next post for the data
Document t = res.parse(); //for later use
SessionID = res.cookie("UNIQUE_NAME");
//the JSON
Connection.Response driverx = Jsoup.connect("https://thewebsite.net/datarequest/data").cookie("UNIQUE_NAME",SessionID).userAgent("Chrome").method(Method.POST).execute();`
I am trying to create new issue at bibucket, but i don't know how to work with http. I try many things but it stil dosen't work. This is one of my attempts:
URL url = new URL("https://api.bitbucket.org/1.0/repositories/"
+ accountname + "/" + repo_slug + "/issues/"
+ "?title=test&content=testtest");
HttpsURLConnection request = (HttpsURLConnection) url.openConnection();
request.setRequestMethod("POST");
consumer.sign(request);
request.connect();
I don't have a problem with GET requests. But here I don't know how to send parametrs and sign the message.
Here is documentation of API
https://confluence.atlassian.com/display/BITBUCKET/issues+Resource#issuesResource-POSTanewissue
How to do this properly?
In the end I figured this out. The parametrs isn't part of the URL, but if you use stream, You can't sign it.
The solution is use Apache HttpComponents library and add parameters like in code below:
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://api.bitbucket.org/1.0/repositories/"
+ accountname + "/" + repo_slug + "/issues/");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("title", "test"));
nvps.add(new BasicNameValuePair("content", "testtest"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
consumer.sign(httpPost);
HttpResponse response2 = httpclient.execute(httpPost);
try {
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
httpPost.releaseConnection();
}
}
But you must use CommonsHttpOAuthConsumer which is in special signpost library for commonshttp.
I have seen you've already solved but here it says that you need to authenticate with OAuth and in the page you linked that you need to authenticate in order to create new issues.
It also links to this page for OAuth implementations for many languages. I am going to post it for knowledge.
I've researched all the internet and found articles on How to use http post from android to php server. I'm not looking for examples of how to pass data from android to website. I'm looking for reasons why POST variable is always NULL in PHP. Is there some setting I need to check for on PHP (I've checked the output buffering, max post, etc) or import a class for the HTTP POST to work correctly for POST variable.
The below codes basically insert values into mysql database. Because the POST variables are blank, it's inserting blank rows. This verified that it's connecting to my server/database, but the POST values are not being passed. Any idea? =)
Below are the codes:
//Java Code-------------------------------------------------
public static void executeHttpGet(Context context, String urlName){
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
String postURL = G.GetUrl(urlName);
HttpPost httpPost = new HttpPost(postURL);
httpPost.setHeader("Accept", "text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try {
nameValuePairs.add(new BasicNameValuePair("value1", "My Name"));
nameValuePairs.add(new BasicNameValuePair("value2", "My Address"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httpPost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
//PHP code ----------------------------------------------------
connectMySQL();
mysql_query("
INSERT INTO myhome(myname,myaddress,createdate)
VALUES('{$_POST['value1']}','{$_POST['value2']}',NOW())
;")
or die(mysql_error());
Can you try to print $_POST['value1'] and $_POST['value2'] before using them in your SQL and see what they print?
For the sake of simplicity I would suggest you rewrite your PHP code:
connectMySQL();
$value1 = trim($_POST['value1']);
$value2 = trim($_POST['value2']);
if ($value1 != "" && $value2 != "") {
mysql_query("
INSERT INTO myhome(myname,myaddress,createdate)
VALUES('".$value1."','".$value2."',NOW())
;")
}
Also, once you have verified it is working, I highly recommend you read about SQL injection attacks and try to use bind variables or parameterized queries instead of directly using request parameter values in your SQL statement.
Retrieving data from the REST Server works well, but if I want to post an object it doesn't work:
public static void postJSONObject(int store_type, FavoriteItem favorite, String token, String objectName) {
String url = "";
switch(store_type) {
case STORE_PROJECT:
url = URL_STORE_PROJECT_PART1 + token + URL_STORE_PROJECT_PART2;
//data = favorite.getAsJSONObject();
break;
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost postMethod = new HttpPost(url);
try {
HttpEntity entity = new StringEntity("{\"ID\":0,\"Name\":\"Mein Projekt10\"}");
postMethod.setEntity(entity);
HttpResponse response = httpClient.execute(postMethod);
Log.i("JSONStore", "Post request, to URL: " + url);
System.out.println("Status code: " + response.getStatusLine().getStatusCode());
} catch (ClientProtocolException e) {
I always get a 400 Error Code. Does anybody know whats wrong?
I have working C# code, but I can't convert:
System.Net.WebRequest wr = System.Net.HttpWebRequest.Create("http://localhost:51273/WSUser.svc/pak3omxtEuLrzHSUSbQP/project");
wr.Method = "POST";
string data = "{\"ID\":1,\"Name\":\"Mein Projekt\"}";
byte [] d = UTF8Encoding.UTF8.GetBytes(data);
wr.ContentLength = d.Length;
wr.ContentType = "application/json";
wr.GetRequestStream().Write(d, 0, d.Length);
System.Net.WebResponse wresp = wr.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(wresp.GetResponseStream());
string line = sr.ReadToEnd();
Try setting the content type header:
postMethod.addRequestHeader("Content-Type", "application/json");
Btw, I strongly recommend Jersey. It has a REST client library which makes these kind of things much easier and more readable
Your C# is different than your Java, and not just in syntax.
Your C# sends an application/json entity to the server via HTTP POST. I'll leave it up to HTTP purists as to whether that's appropriate use of POST (vs. PUT).
Your Java creates a form, with a field of jsonString (whose value is the JSON), and sends an application/x-www-form-urlencoded entity to the server containing that form.
I would go right to the server err_log or equivelant error log. The server knows why it rejected your request. If you don't have access, set up your own test server and duplicate the issue there so you can review the logs =)