store and get cookies for the code using HttpURLConnection - android

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 !!

Related

How to add cookie to url using HttpUrlConnection class in android?

I'm trying to parse the json data from an url, when i try to create connection , it throws the exception as
java.net.ProtocolException: cannot write request body after response has been read
I got the response message as Not found.
and i checked the url in web browser it shows the Json data when i login wuth my credentials.
so, i found that i need to add the cookie to my connection, but i don't know how to do this.
public void parseData(String cookie){
HttpUrlConnection connection;
try{
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Cookie", cookie);
Log.e(TAG, "cookie " + cookie);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.connect();
Log.e(TAG,connection.getResponseMessage());
/**
here i'm trying to parse the data
using BufferedReader calss
**/
}
catch(IOException e){}
}
i need to add the cookie in connection.
Please help me on this.
According to this link
you can do this:
Values must be set prior to calling the connect method:
URL myUrl = new URL("http://www.hccp.org/cookieTest.jsp");
URLConnection urlConn = myUrl.openConnection();
Create a cookie string:
String myCookie = "userId=igbrown";
Add the cookie to a request: Using the
setRequestProperty(String name, String value); method, we will add a
property named "Cookie", passing the cookie string created in the
previous step as the property value.
urlConn.setRequestProperty("Cookie", myCookie);
Send the cookie to the server: To send the cookie, simply call connect() on the URLConnection
for which we have added the cookie property:
urlConn.connect()

Android - Using HttpURLConnection to POST XML data

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.

Dont how to replace BasicValueNamePair as its deprecated

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

How to get the HTMl page of redirected page using HttpURLConnection with Jsoup

I am trying to get the html page of the redirected page using HttpURLConnection. The initial page is login and I am getting redirected from that to the next page. I am also getting the URL of the newly directed page also but when I get the html content of the newly directed page it returns the login page html view. The code is below plz help out.
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(urlNew).get();
Login page Elements docEle = doc.select("#header a");
HTML Log.v("Document", docEle.toString() );
}
catch (Exception e) {
Log.v("Error", e.toString());
}
To set VM-wide cookie (in memory), use the code below:
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
Then after loggin in, you need to pass the cookie to Jsoup, something like the below example (modify as needed for you case)
Jsoup.connect("https://need.authentication.com").cookie(urlNew, cookie).get()

Not able to insert data to mysql via servlet

I am trying to insert data to a mysql table using the below methods but am not able to do so. Any idea on where I may be going wrong?
Method 1: Using HTTPClient to directly access the URL. Below is the code:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://<lclhst>/GnPServlet/GetNpostServlet/? account=1&password=123");
HttpResponse execute = client.execute(httpPost);
Method 2: Using URL connection to directly access the URL. Below is the code:
URL url = new URL("http://<lclhst>/GnPServlet/GetNpostServlet/? account=1&password=123");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Accept", "application/octet-stream");
conn.connect();
Method 3: Using Arraylist to pass values.
When i run the URL from the browser i get the success message "Inserted" and the data is inserted into the DB. But the same when tried through the app does not insert data. Below is the servlet code:
private String accountLookup(String acct, String pwd)
{
Connection con = null;
Statement st = null;
StringBuffer msgb = new StringBuffer("");
try
{
// These will vary depending on your server/database
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbone?user=root&password=root");
Statement stmt = con.createStatement();
stmt.executeUpdate("insert into accttbl(address, description, time) values ('test 07-jul',ok,12:12)");
return "Inserted";
}
catch (Exception e)
{
return e.toString();
}
}
The below code inserts data but it opens the browser which I dont want. Also the data insertion is not always successful.
String url = "http://10.0.2.2:8080/GnPServlet/GetNpostServlet";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
conn.setRequestMethod("POST");
Looks like you're sending a POST when the servlet expects a GET (which is what the browser would send if you just paste the URL into the URL bar)
conn.setRequestMethod("GET");
...is most likely what you want since your parameters are encoded in the URL.
Also, are you sure that the spaces in your URL before account should be there?

Categories

Resources