This is my code below trying to create a login page using PHP, mysql and xampp server. I am having problem with BasicValueNamePair as it is deprecated. I dont know how to replace with new code. Any help please
URL url = new URL("http://10.0.3.2/android_api/check.php");
HttpURLConnection urlConnection =(HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String res = IOUtils.toString(in, "UTF-8");
System.out.println(res + " Blu bluh");
// make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name
// and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("Username",username.getText().toString().trim()));
//$Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("Password",password.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
HttpURLConnection is derived from URLConnection so you can
use the addRequestProperty to include your name-value pairs.
urlConnection.addRequestProperty("Username",username.getText().toString());
See details here
Related
I used HttpPost and HttpURLConnection in Android to send the request with following Headers and Contents:
Headers:
api_key: 9a8akx8badkaxxxx,
speed: 0,
voice: male,
prosody: 1,
Cache-Control: no-cache
Contents (with Content-Type: text/plain):
Hello everyone
These are my code:
*Using the HttpPost:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(requestURL);
post.addHeader("api_key", "9a8akx8badkaxxxx");
post.addHeader("speed", "0");
post.addHeader("voice", "male");
post.addHeader("prosody", "1");
post.addHeader("Cache-Control", "no-cache");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("data[body]", "Hello everyone"));
AbstractHttpEntity ent= null;
ent = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
ent.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
ent.setContentEncoding("UTF-8");
post.setEntity(ent);
post.setURI(new URI("http://api.openfpt.vn/text2speech/v4"));
HttpResponse response =client.execute(post);
*Using the HttpURLConnection:
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("api_key", "9a8akx8badkaxxxx");
conn.setRequestProperty("Content-Type", "text/plain");
conn.setRequestProperty("speed", "0");
conn.setRequestProperty("voice", "male");
conn.setRequestProperty("prosody", "1");
conn.setRequestProperty("Cache-Control", "no-cache");
and then I don't know the method to put the content "Hello everyone" into HttpURLConnection
The result always error. But when I use the add-on HttpRequester in Firefox, the response is OK.
please help me to create and set Http Request in Android
Try this to set the content-type:
HttpPost httppost = new HttpPost(builder.getUrl());
httppost.setHeader(HTTP.CONTENT_TYPE,
"text/plain;charset=UTF-8");
To set arbitrary headers, I believe it should be done like this:
httppost.setHeader("api_key", "9a8akx8badkaxxxx");
httppost.setHeader("speed", "0");
httppost.setHeader("voice", "male");
httppost.setHeader("voice", "male");
httppost.setHeader("prosody", "1");
httppost.setHeader("Cache-Control", "no-cache");
To send the data, choose a name for your post field (here Fn and IdDevice):
List<NameValuePair> nameValuePairs = new ArrayList<>(1);
// nameValuePairs.add(new BasicNameValuePair("Fn",function));
// nameValuePairs.add(new BasicNameValuePair("IdDevice",IdDevice));
EDIT START
nameValuePairs.add(new BasicNameValuePair("Content","Hello everyone"));
EDIT END
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
And finally, execute the post request:
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
I've run into a bit of a deadend and need a bit of help (please)!
I'm very new to Android Dev (and to coding in general). Basically I need to POST XML data to a URL using HttpURLConnection but can't get it to work. I've got my app reading and pasrsing XML data from a GET request but finding the POST part difficult.
I've looked at creating a NameValuePair array but not sure how to do this with the XML structure I am needing to post.
The XML data will look like this:
<Sheet>
<Job>jobNumber</Job>
<Task>taskNumber</Task>
<UserID>3</UserID>
<Date>systemDateFormatted</Date>
<Minutes>timeToLog</Minutes>
<Note>userNote</Note>
</Sheet>
So far I have this for my code.
try {
URL url = new URL(theUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Sheet", null));
params.add(new BasicNameValuePair("Job", jobNumber));
params.add(new BasicNameValuePair("Task", taskNumber));
params.add(new BasicNameValuePair("UserID", String.valueOf(yourUserID)));
params.add(new BasicNameValuePair("Date", systemDateFormatted));
params.add(new BasicNameValuePair("Minutes", timeElapsed));
params.add(new BasicNameValuePair("UserNote", "Test Note"));
params.add(new BasicNameValuePair("Sheet", null));
I'm not sure if I'm understanding NamedValuePair right. Would it be better to create a string for my XML data and POST this way instead?
Thanks!
Yes, POST data goes as payload of your request. For example
URL url = new URL(theUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
try {
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
String body = "<xml...</xml>";
OutputStream output = new BufferedOutputStream(conn.getOutputStream());
output.write(body.getBytes());
output.flush();
finally {
conn.disconnect();
}
I'm not sure if I'm understanding NamedValuePair right. Would it be better to create a string for my XML data and POST this way instead?
Your post seems to be cut off, but from what you show what you're doing is not posting XML but adding query parameters.
Convert your XML to an encoded string, then write it to the output stream you get from conn.getOutputStream().
Here's a similar example: https://stackoverflow.com/a/2737455/1197251
You would replace "query" with your XML string.
I am not getting how to store and get back cookies and checked with example programs also in this code I am trying to login with a url with username and pass credentials after that getting redirected to new page. I am trying to get the HTml content of the redirected page. But I need to pass the cookie to jsoup inorder to get the HTml content of the redirected page. I dont to store and get back cookies. Plz help me with code how to store and get back the cookies and pass it to the jsoup.
protected Object doInBackground(Object... params) {
try {
old URL--->URL url = new URL(UrlLink);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
List<NameValuePair> login = new ArrayList<NameValuePair>();
login.add(new BasicNameValuePair("login", "xxxxx"));
login.add(new BasicNameValuePair("password", "yyyyyy"));
login.add(new BasicNameValuePair("Login", "Login"));
login.clear();
int responseCode = urlConnection.getResponseCode();
System.out.println(responseCode);
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
New Url---> URL newURL = urlConnection.getURL();
String urlNew= newURL.toString();
Returns--> doc=Jsoup.connect(res).data("login", "xxxxxxx")
.data("password", "ramesh88").get();
Login page Elements docEle = doc.select("#header a");
HTML Log.v("Document", docEle.toString() );
}
catch (Exception e) {
Log.v("Error", e.toString());
}
Following links would be helpful:
HOW-TO: Handling cookies using the java.net.* API
How to handle cookies in httpUrlConnection using cookieManager
Cheers !!
I want to post to this url
http://abc.com/Registration.aspx?MailID=PickUp&UserName=as&PickUpTime=19191919&Notes=bla&DeviceId=0000
HttpPost httppost = new HttpPost("http://abc.com/Davis/Registration.aspx");
httppost.setHeader("MailID","MailID=PickUp");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//nameValuePairs.add(new BasicNameValuePair("MailID","PickUp"));
nameValuePairs.add(new BasicNameValuePair("UserName","as"));
nameValuePairs.add(new BasicNameValuePair("PickUpTime",date));
nameValuePairs.add(new BasicNameValuePair("Notes",note));
nameValuePairs.add(new BasicNameValuePair("DeviceId",deviceID));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
Also how can I know what url I am passing . How can I log it ?
Are you sure MailID should be in the header? From the wording of the question, it looks as if all values are in the query string (in the URL past the ? mark). But then why would you need POST for that; a GET would be sufficient.
And passing data, like MailID, in headers is almost unheard of. Querystring and POST form, those are the most popular places.
So first figure out the interface of the server page. Does it expect GET or POST (or either)? Then place the fields into the right place - either into the URL (by string concatenation), or into the entity.
Oh, and the URL you're passing is http://abc.com/Davis/Registration.aspx. Neither setHeader() nor setEntity() modifies the URL per se.
I am able to do a POST of a parameters string. I use the following code:
String parameters = "firstname=john&lastname=doe";
URL url = new URL("http://www.mywebsite.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(parameters);
out.flush();
out.close();
connection.disconnect();
However, I need to do a POST of binary data (which is in form of byte[]).
Not sure how to change the above code to implement it.
Could anyone please help me with this?
Take a look here
Sending POST data in Android
But use ByteArrayEntity.
byte[] content = ...
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new ByteArrayEntity(content));
HttpResponse response = httpClient.execute(httpPost);
You could base-64 encode your data first. Take a look at the aptly named Base64 class.
These links might be helpful:
Android httpclient file upload data corruption and timeout issues
http://getablogger.blogspot.com/2008/01/android-how-to-post-file-to-php-server.html
http://forum.springsource.org/showthread.php?108546-How-do-I-post-a-byte-array