I need a simple androd application, which POST a word to the server and recive the answer from server. I creat a form, which have two line and one button. In first line user write the word and click the button. In this time the app send this word to the server. When server send back response we show this respons in other line.
I right some code but this code don`t work on android 23. I also try to do this with retrofit, but I have varios problem with understending of this fiture.
I know that just need use POST, but don`t know how.
And can I send the ip adress of my android to the server?
Try this code:
It will also return the response from that page as a String
public static String postRequest(String post_url, String data) {
try {
URL url = new URL(post_url);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
BufferedReader br;
StringBuilder sb = new StringBuilder();
String line;
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setReadTimeout(10000);
Writer writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(data);
writer.flush();
writer.close();
if (200 <= connection.getResponseCode() && connection.getResponseCode() <= 299) {
br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
} else {
br = new BufferedReader(new InputStreamReader((connection.getErrorStream())));
}
while ((line = br.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
And call it by:
postRequest("http://your-url", "name=value&anothername=somevalue");
I think volley will fit your needs, it's a very simple library that can handle asynchronous requests :
https://developer.android.com/training/volley/index.html
"And can I send the ip adress of my android to the server?"
Sure, to get your android ip just use a code like this on server side, assuming you're using PHP :
<?
$ip = $_SERVER["REMOTE_ADDR"];
echo "<br />Your IP is : $ip";
?>
EDIT : NodsJS example
app.post('/getip', function (req, res) {
var ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
})
Related
I want to share database between an android application and a web application build using Asp.net (my database is based on an IIS server.)
I just want to find the possible ways available to do it, and if I could use php services with IIS server.
I would be so thankful if someone could help me.
Million ways. I can advise you this one: create REST or SOAP service which will have access to database with all methods you need. Now in android application and in ASP.NET application you can "ask" your service to create/update/delete/do something.
try with below code.Hope it will resolved your query.
/**
* This method is used for getting user response after sending request to server.
* It returns the response after executing url request.
* #param params
* #return
*/
public String getJSONObject(String params)
{
try
{
URL url = null;
String response = null;
String parameters = "param1=value1¶m2=value2";
//url = new URL("http://www.somedomain.com/sendGetData.php");
url = new URL(params);
//create the connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setReadTimeout(40000);
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
//set the request method to GET
connection.setRequestMethod("GET");
//get the output stream from the connection you created
OutputStreamWriter request = new OutputStreamWriter(connection.getOutputStream());
//write your data to the ouputstream
request.write(parameters);
request.flush();
request.close();
String line = "";
//create your inputsream
InputStreamReader isr = new InputStreamReader(
connection.getInputStream());
//read in the data from input stream, this can be done a variety of ways
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
//get the string version of the response data
response = sb.toString();
//do what you want with the data now
//always remember to close your input and output streams
isr.close();
reader.close();
}
catch (Exception e)
{
Log.e("HTTP GET:", e.toString());
response="";
}
return response;
}
I have been running into a very strange problem. I am trying to implement log in service in my app. When I pass right email and password service returns response as expected(means no error comes) but when I delibrately pass wrong email or password geInputStream() method throws FileNotFoundException. I don't know what is the reason behind this.Further more, before calling getInputStream() method i checked status code as well(this is the case when I am passing wrong email and password intentionally).The status code was 500. I checked for 500 and that was internal server error. My question is why is that so? I mean when intentionally passing wrong email or password why internal server occurred? One more thing I would like to mention that I have checked the same service on post man it is working fine as expected. If i pass wrong email or password postman returns the expected error. Below is the code I am using
private String invokeWebservice() {
String data = null;
HttpURLConnection conn = null;
BufferedReader in = null;
try {
String webservice = Constants.BASE_URL + serviceName;
LogUtility.debugLog("webservice just called "+ webservice);
URL url = new URL(webservice);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setUseCaches(false);
if (isPost) {
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
Writer writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
if (jsonObject != null)
writer.write(jsonObject.toString());
writer.close();
}
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) != null)
sb.append(l + nl);
in.close();
data = sb.toString();
return data;
} catch (Exception e) {
LogUtility.errorLog("exception while calling web service");
} finally {
try {
if (conn != null)
conn.disconnect();
if (in != null)
in.close();
} catch (Exception ex) {
// LogUtility.errorLogWithException(ex, ex.getMessage());
}
}
return data;
}
Any help?
After spending some time now I was able to solve my problem.Posting my answer for others. Passing wrong email and password to the service was right and server was consuming those parameters as well and because there was an error(because email and password) that is why it was returning 500 code. So, I checked for status code if it was 200 then I used getInputStream() method and else i called getErrorStream() method. By this way i got the stream that has property for error(this property contains error detail). Below is the code i used
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
} else {
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
}
Hope it helps other as well.
Today I'm making my first attempt of sending a POST request with a JSON to save some data, and I'm not being able to do so.
My app works by signing in, and then save, modify and delete data. It's already done in iOS, but since I'm new to Android, I'm not sure how to do it.
Here's my POST function:
public String POST(String targetURL, String urlParameters, String user, String pwd) {
URL url;
String u = targetURL;
HttpURLConnection connection = null;
try {
// Create connection
// u=URLEncoder.encode(u, "UTF-8");
url = new URL(u);
connection = (HttpURLConnection) url.openConnection();
// cambiarlo luego al usuario q esta logeado
String login = user + ":" + pwd;
String encoding = new String(org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(login)));
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Basic " + encoding);
connection.setRequestProperty("Content-Type", "plain/text");// hace q sirva con el string de json
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setReadTimeout(120000);
// Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
this.setResponseCode(connection.getResponseCode());
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
The method above is executed with Asynctask, and even if I use it to Login using Spring security, it works, and even I can save for internal usage the username, password, and secret token.
I dunno if I need to put the token in a header or something, because I already did that, with no positive results.
I'm supposing that the only permission I need to execute this is the internet one, so in my manifest file I specified that permission.
I'm going crazy with this issue, please help!
Thanks in advance.
EDIT:
Sorry guys, I'm kinda new to this way of asking, and also, not an English native speaker :P
The output I receive after sending the request, is the HTML of the page that handles logging in into the web app... I need like a json response or something like that to make sure the request was saved correctly
Try handling your cookies
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
This should be a singleton.
First, sorry for my poor English.
I found this article and follow it.
https://developers.google.com/appengine/articles/soap?hl=vi
It's worked. Now i want to create only the server like that to use in other client.Is that ok?
For example when i deployed the HelloSOAPServerServlet to the abc#appspot.com
And when i want to use my service, i just paste this URL: abc#appspot.com/hellosoapserver?name=SOAP&arriving=true to the browser. How can i do something like that?
Because i want my client what use this service is the Andoird phone.
abc#appspot.com is an email address. You can not deploy GAE code to it.
When you create a GAE application you must pick a unique application name, for example mysoap. The url of your app would then be http://mysoap.appspot.com/.
After you upload your code to it you could access your SOAP at http://mysoap.appspot.com/hellosoapserver?name=SOAP&arriving=true
You got it in that example.
You made the SOAP Webservice in :
Building a SOAP Server on Google App Engine
and then you created a client that consume it from a Servlet:
Building a SOAP Client on Google App Engine Using JAX-WS
Now what you need is to make a HTTP Client call to that URL from your Android application with correct values in params.
Using the example available at http://developer.android.com/reference/java/net/HttpURLConnection.html and url provided your sample
URL url = new URL(" http://greeter-client.appspot.com/hellosoapclient?name=SOAP&arriving=true");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
In readStream is where you read the response from your service hosted at GAE
readStream can be something like this:
private static String readStream(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
First, I want to connect to the site.
After, I want to get a data from different page with this connection
sample:
1- connect to http://site.com/Login with user pass
2- get a secret data from http://site.com/Secret
How do I do this, pleas help me...
OutputStreamWriter request = null;
url = new URL("http://site.com/Login");
String response = null;
EditText user = (EditText)this.findViewById(R.id.user);
EditText pass = (EditText)this.findViewById(R.id.pass);
String parameters ;
try {
System.setProperty("http.keepAlive", "true");
url = new URL("http://site.com/Home/Login");
httppost = (HttpURLConnection) url.openConnection();
httppost.setDoInput(true);
httppost.setDoOutput(true);
httppost.setRequestMethod("POST");
httppost.setRequestProperty("User-Agent", "Mozilla/5.0 Linux U Android 2.3.3 tr-tr HTC_DesireHD_A9191 Build/GRI40 AppleWebKit/533.1 KHTML, like Gecko Version/4.0 Mobile Safari/533.1");
httppost.setRequestProperty("Accept_Language", "en-US");
httppost.setRequestProperty("Connection", "Keep-Alive");
httppost.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
request = new OutputStreamWriter(httppost.getOutputStream());
parameters = "username="+user.getText()+"&password="+pass.getText();
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(httppost.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
response = sb.toString();
Toast.makeText(this,response, Toast.LENGTH_LONG).show();
isr.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
You should use WebView and sorry but you can not get the webview content.
If you own the server-side code and you want to access from java then you should use an access token for more secure connection and get data by using JSON or XML. Or there is a much more secure connection type which is OAuth2.
If you don't own server, you should show the http://site.com/Login url in webview. When the user logins than you have cookie in your webview. You can use CookieManager http://developer.android.com/reference/android/webkit/CookieManager.html and send the data by using this cookie and get the result. This method is not easy and can differentiate according to server-side implementation.