I am trying to login to a webside which needs 3 parameters in the post command.
Token, usr_name and usr_password.
The token always has the following value "545616f1e29bc538843ec7aa908122b1e".
I am getting this value by doing a HttpGet on the loginpage and store it as a string.
If i do a login through the url as follows https://www.xxxxx.com/xxxx/restricted/form/formelement=0123?usr_name=myuser&usr_password=mypass&token=545616f1e29bc538843ec7aa908122b1e the login succeeds.
How do i get a.m link build together and know afterwards that i successfully logged in?
Thanks for any tips and helping me out.
My code:
try {
String webPage = "https://xxxxxxxx.com/xx/Authenticationserv";
String name = username; // user input through editbox
String password1 = password; // user input through editbox
String authString = name + ":" + password1 + ":" + token + "=" + value;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBytesToBytes(authString.getBytes());
String authStringEnc = new String(authEncBytes);
System.out.println("Base64 encoded auth string: " + authStringEnc);
URL url = new URL(webPage);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb1 = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb1.append(charArray, 0, numCharsRead);
}
String result = sb1.toString();
System.out.println("/// BEGIN ///");
System.out.println(result);
System.out.println("/// END ///");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
Actually I think you need to use POST method to log in in your website.I had the same problem a few weeks ago and I've did this :
HttpClient httpclient;
HttpPost httppost;
ArrayList<NameValuePair> postParameters;
httpclient = new DefaultHttpClient();
httppost = new HttpPost("your login link");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username_hash", "fcd86e8cc9fc7596f102de7b2b922e80c6e6fac9"));
postParameters.add(new BasicNameValuePair("password_hash", "b66936348bd0bd44fa44f5ca7dcceb909545e47f"));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.w("Response ","Status line : "+ response.toString());
So you are setting up your post params with an ArrayList and you can get the responce from the server if you logged in via HttpResponse.And another thing : I'm setting up the username and password in the code,because it is just to how you the idea.If you have any questions feel free to ask.
Hope it helps!
Related
When I used HttpUrlConnection to send POST request from Android to ASP.net Web API. It seems not working.
String baseUrl = "http://<IP Address>/Save/Document";
URL url = new URL(baseUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
JSONObject ap = new JSONObject();
// Where data is a JSON string
// Like [{Test: 1}, {Test: 2}]
ap.put("",new Gson().toJson(data));
OutputStreamWriter ap_osw= new OutputStreamWriter(conn.getOutputStream());
ap_osw.write(ap.toString());
ap_osw.flush();
ap_osw.close();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder response = new StringBuilder();
while ((output = br.readLine()) != null) {
response.append(output);
response.append('\r');
}
String mes = response.toString();
Log.i("INFO", mes);
conn.disconnect();
When executing the above code, it will have an FileNotFoundException in
conn.getInputStream()
I also tried to implement source code in HttpClient style.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(baseUrl);
try {
StringEntity se = new StringEntity((new Gson()).toJson(data));
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpPost);
InputStream inputStream = response.getEntity().getContent();
String result = "";
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
Log.i("RESPONSE", result);
} catch (Exception ex) {
Log.i("Exception", ex.getMessage());
}
return output;
And this time, it shows "The requested resource does not support http method 'get'".
I have no ideas how to implement the POST request method to send data from Android to ASP.net Web API. Any recommendations?
Finally, the following coding is my ASP.net Web API for reference.
[HttpPost]
[Route("Save/Document")]
public HttpResponseMessage Post([FromBody]string model)
{
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(model, System.Text.Encoding.UTF8, "text/plain");
return resp;
}
Finally, I got a solution to fix this problem. It is due to the POST data in request body can not be read from Web API.
When the request Content-Type is "application/json",
Using string, The request body should be a plain text (e.g. "Text Message").
[FromBody] string inStr
Using self-defined class, The request body should be a json string
(e.g { KEY: VALUE })
[FromBody] YourClass inObj
Using array of self-defined class, The request body should be a json array string (e.g [{ KEY: VALUE }])
[FromBody] YourClass[] inObj
And the self-defined class should be like as following:-
class YourClass {
public string KEY { get; set; }
}
Btw. Thanks for all reply and useful information.
I am trying to make a login and register for an android app.
I have been having problems adjusting the code to API 22.
Although I know I have to use HttpURLConnection instead of HttpRequestParams etc., and have done that, I can't figure out how to adjust the code to incorporate the database server and my PHP files stored on there.
It's mostly this bit below that I can't figure out.
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");
Can anyone help? Thanks in advance.
Here's the full code:
#Override
protected User doInBackground(Void... params) {
ContentValues contentValues = new ContentValues();
contentValues.put("username", user.username);
contentValues.put("password", user.password);
URL url = new URL(SERVER_ADDRESS);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setReadTimeout(CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");
User returnedUser = null;
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
HttpResponse httpResponse = client.execute(post);
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
JSONObject jObject = new JSONObject(result);
if(jObject.length() == 0) {
returnedUser = null;
} else {
String mobile = jObject.getString("mobile");
String email = jObject.getString("email");
returnedUser = new User(mobile, email, user.mobile, user.email);
}
} catch(Exception e) {
e.printStackTrace();
}
return returnedUser;
}
first: It's already been answered
Sending Http request for Android 22+
second: I've made a class that meets your needs, which allow you to send request and receive response with one line of code (It's also explained in post above)
Here is the link for the my class:
HttpRequest
I'm trying to send json data to a php script from my Android application with HttpClient, and get the response.
Android Code
private void sendPurchase(String SKU) throws IOException{
Log.e("sendPurchase","Inside sendPurchase");
final SharedPreferences prefs = getGCMPreferences(getApplicationContext());
int pur_user = prefs.getInt("C_user", Integer.MIN_VALUE);
InputStream inputStream = null;
String result = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.*.com/includes/purchase.php");
JSONObject json = new JSONObject();
try {
json.put("PUR_sku", SKU);
json.put("PUR_user", pur_user);
} catch (JSONException e) { Log.e("SendPurchase","Problem with Json Object"); }
Log.i("JSONObject", json.toString());
StringEntity se = new StringEntity(json.toString(), HTTP.UTF_8);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null){ result = convertInputStreamToString(inputStream); }
else{result = "Did not work!"; }
Log.e("RESULT",result);
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
And the PHP script
<?
$auth=0;
require('./connexion.php');
$data = file_get_contents('php://input');
//$data = '{"PUR_sku":"singleone","PUR_user":"3"}';
$json = json_decode($data,true);
/* Some database stuff ... */
echo "Retour ".print_r($json)." et ".$json['PUR_sku']." et ".$json['PUR_user'];
?>
When i launch the app and execute sendPurchase function, it seems to be ok until the execution of the HttpPost. In the logcat i get all the logs with correct params, except the last log "RESULT" that does not appear.
That's why i guess something is going wrong with the HttpPost execution, but actually i don't know if the problem comes from the application side or the php script side...
When i execute the php script alone in a web browser, replacing first $data line by the second one, everything is ok. But when it comes from the application it's not ok...
The Json Object sent (i hope) to the script seems ok too : {"PUR_user":3,"PUR_sku":"singleone"}
(the sendPurchase function is executed in Background).
Any idea about what i'm doing wrong ? Thanks !
/EDIT/
Here is the logcat for #RyuZz solution.
My code is about purchasing an item, consume it and send new value to my database on a web server. The purchase & consume are ok, but i can't send the values to the web server.
And again, when i execute the php script alone in a web browser, replacing first $data line by the second one, everything is ok.
Note that i have another similar code to register user to GCM, using HttpClient, and that code works fine.
06-25 14:07:12.968: D/IabHelper(21833): Successfully consumed sku: singleconf
06-25 14:07:12.968: D/IabHelper(21833): Ending async operation: consume
06-25 14:07:12.979: D/CONSUME(21833): Consumption finished. Purchase: PurchaseInfo(type:inapp):{"orderId":"12999763169054705758.1353445524837889","packageName":"com.*.*","productId":"singleconf","purchaseTime":1435234296875,"purchaseState":0,"purchaseToken":"bohbcbiigcbidfficbikebnk.AO-J1OzuQ_SsNTG1h9MtUvbaPc3PeN9nBHG-qBOE82ao1rTDFNrgA7tYQcMdECxCVFrrZEn_QifQ28OcIupyesZI-5cjDILFODYpBEaeqMfE0wCAeMFkJLfNUK_TsKPMj7F2sBDdgOYx"}, result: IabResult: Successful consume of sku singleconf (response: 0:OK)
06-25 14:07:12.979: D/CONSUME(21833): You bought & consumed a single conf
06-25 14:07:12.979: D/CONSUME(21833): End consumption flow.
06-25 14:07:12.979: E/Purchase Background(21833): Inside doInBackground
06-25 14:07:12.979: E/sendPurchase(21833): Failed to send HTTP POST request due to: java.lang.NullPointerException
You can try the following instead of HttpClient which is anyway deprecated:
try{
int pur_user = prefs.getInt("C_user", Integer.MIN_VALUE);
URL url = new URL("http://www.*.com/includes/purchase.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestMethod("POST");
JSONObject jsonObject = new JSONObject();
jsonObject.put("PUR_sku", SKU);
jsonObject.put("PUR_user", pur_user);
//convert JSONObject to JSON to String
json = jsonObject.toString();
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(json);
writer.close();
responseCode = connection.getResponseCode();
if(responseCode == 200) {
InputStream content = connection.getInputStream();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(content, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
{
sb.append(line).append("\n");
}
result = sb.toString();
//TODO get your stuff from result
content.close();
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
} finally {
connection.disconnect();
}
} else {
Log.e(TAG, "Server responded with status code: " + responseCode);
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
}
if this isn't working, please post the logcat.
Don't forget to implement the required permissions in your manifest:
<uses-permission
android:name="android.permission.INTERNET" />
A friend have a Rest API with Django, and Im trying to make and android app for it, but I having problems with the authentication.
First i get the CSRF token, just making a get call and taking the value.
public String getCFSRToken() throws Exception{
String csrftokenValue="";
httpClient.execute(new HttpGet(urlBasic));
cookieStore = httpClient.getCookieStore();
List <Cookie> cookies = cookieStore.getCookies();
for (Cookie cookie: cookies) {
Log.v("csrftoken",cookie.getName());
if ( cookie.getName().compareTo("csrftoken")==0) {
csrftokenValue = cookie.getValue();
}
}
return csrftokenValue;
}
Then I try to make the authentication:
public void login3() throws Exception{
String urlLogin ="/login";
String url = urlBasic+urlLogin;
String username = "jesus.m.martinez.garcia";
String password = "lolofree";
String userpass = username +":"+password;
HttpPost post = new HttpPost(url);
// List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
// nameValuePairs.add(new BasicNameValuePair("username", username));
// nameValuePairs.add(new BasicNameValuePair("password", password));
// post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String basicAuth = "Basic " + new String(Base64.encode(userpass.getBytes(),Base64.NO_WRAP ));
post.addHeader("Authorization", basicAuth);
post.addHeader("X-CSRFToken", getCFSRToken());
HttpResponse response = httpClient.execute(post);
CookieStore as = httpClient.getCookieStore();
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
String pagina="";
while ((line = rd.readLine()) != null) {
pagina= pagina + "\n"+line;
}
System.out.println(pagina);
}
If I don't add the CSRF header I receive always a 403 Forbidden, so I suppose that part is correct, but when I try to do the login with the post (as you can see I have try without codification and basic), I always receive a 200 Ok, but I receive an HTML page for logging and I don't get the session cookie, that's what is killing me.
I asked my friend and he told me, he didn't modify the authentication of Django framework, so I suppose is not digest. Any idea what I am doing wrong?
Thank you in advance ;)
I am having an Android Activity which I want to connect with MYSql database with JSP page as middle layer to accept values from android and do query on databse.
Problem is I'm not able to send parameter values from Android Activity to JSP page. Application crashes as Emulator starts. I have given permission for internet in manifest file, This catches exception.
public void tryLogin() {
Log.v(TAG, "Trying to Login");
EditText etxt_user = (EditText) findViewById(R.id.txt_username);
EditText etxt_pass = (EditText) findViewById(R.id.txt_password);
String username = etxt_user.getText().toString();
String password = etxt_pass.getText().toString();
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:8084/authen/register.jsp");
List< BasicNameValuePair > nvps = new ArrayList< BasicNameValuePair >();
nvps.add(new BasicNameValuePair("username", username));
nvps.add(new BasicNameValuePair("pass", password));
try {
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,"utf-8");
httppost.setEntity(p_entity);
HttpResponse response = client.execute(httppost);
Log.v(TAG, "Sahil Sahil Sahil");
Log.v(TAG, response.getStatusLine().toString());
HttpEntity responseEntity = response.getEntity();
Log.v(TAG, "Set response to responseEntity");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
LoginHandler myLoginHandler = new LoginHandler();
xr.setContentHandler(myLoginHandler);
xr.parse(retrieveInputStream(responseEntity));
ParsedLoginDataSet parsedLoginDataSet = myLoginHandler.getParsedLoginData();
if (parsedLoginDataSet.getExtractedString().equals("SUCCESS")) {
// Store the username and password in SharedPreferences after the successful login
SharedPreferences.Editor editor=mPreferences.edit();
editor.putString("UserName", username);
editor.putString("PassWord", password);
editor.commit();
Message myMessage=new Message();
myMessage.obj="SUCCESS";
handler.sendMessage(myMessage);
} else if(parsedLoginDataSet.getExtractedString().equals("ERROR")) {
Intent intent = new Intent(getApplicationContext(), LoginError.class);
intent.putExtra("LoginMessage", parsedLoginDataSet.getMessage());
startActivity(intent);
removeDialog(0);
}
} catch (Exception e)
{
Intent intent = new Intent(getApplicationContext(), LoginError.class);
intent.putExtra("LoginMessage", "Unable to login");
startActivity(intent);
removeDialog(0);
}
}
Here you have a small example how to send parameters to a URL...
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
....
String data = URLEncoder.encode("param1", "UTF-8") + "="
+ URLEncoder.encode(param1, "UTF-8");
data += "&" + URLEncoder.encode("param2", "UTF-8") + "="
+ URLEncoder.encode(param2, "UTF-8");
URL url = new URL(http://example.com);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
You can create a JSP page that accepts an XML parameter in GET format, and do operation on that data.
Example:
You create a page like this, which will accept XML formatted data:
http://example.com/api/getdb.jsp?data=XML_FORMATED_DATA
Suppose you have the following XML data:
String sXML = "<xml>" +
"<table>" +
"<row>" +
"<name>Alice</name>" +
"<salary>5000</salary>" +
"</row>" +
"<row>" +
"<name>Bob</name>" +
"<salary>7000</salary>" +
"</row>" +
"</table>" +
"</xml>" ;
Now you just do this in your Android code:
String sUrlEncoded = UrlEncoder.encode(sXML, "utf-8"); // This line encodes XML symbols into URL-friendly characters.
URL url = new URL("http://example.com/api/getdb.jsp?data=" + sUrlEncoded);
URLConnection conn = url.openConnection();
That's all...!
Now you've called your JSP page with the XML data as the GET parameter. In your JSP, you need to retrieve the XML data, and parse it, and perform the operation!
Just like: (I am trying some JSP!)
String pXML = request.getParameter("data");
// Now parse the content of pXML variable!
Tip:
For added security, you can include a spot-generated session-key to the URL like this:
http://example.com/api/getdb.jsp?userid=USER_SESSION_KEY&data=XML_FORMATED_DATA
Working example from my code...
Android
HttpPost post = new HttpPost("http://localhost:8080//AddLocation.jsp");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("id", "007"));
pairs.add(new BasicNameValuePair("name", "James Bond");
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
JSP
request.getParameter("id");
request.getParameter("name");