I'm trying to increase my knowledge to Android and trying to code a small app for my personal needs.
I'm trying to post data via the HTTP Post method on a test server.
The request is sent ok, but now, I'm trying to display the response, which is an HTML page with the dump of my request.
Here is an extract of my code, it is basically a few EditText fields, and button that sends the request.
The following code is the listener for that button.
validateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://posttestserver.com/post.php?dump&html&dir=mydir&status_code=200");
try {
// Gathering data
String value01 = nb01Spinner.getSelectedItem().toString();
String value02 = nb02EditText.getText().toString();
String value03 = nb03EditText.getText().toString();
String value04 = nb04EditText.getText().toString();
// Add data to value pairs
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(04);
nameValuePairs.add(new BasicNameValuePair("test01", value01));
nameValuePairs.add(new BasicNameValuePair("test02", value02)); //
nameValuePairs.add(new BasicNameValuePair("test03", value03));
nameValuePairs.add(new BasicNameValuePair("test04", value04));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
I'm not sure if I need to create another Activity or not... I suppose I also have to create a webview aswell, but I'm a bit lost. For now the "raw" HTML would be fine, but afterwards I will need to parse the data, and extract only the strings I need.
So I would need help (an a good and simple example !)
Thank you.
String ret = EntityUtils.toString(response.getEntity());
Maybe this will help?
Very simple approach is Take textview the way you have taken button widget. and what ever response you got set in the textview. you will be able to see the response. else use the Log to log your response in the logcat.
This is how you get the Http response :
byte[] buffer = new byte[1024];
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://www.rpc.booom.com");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("params","1"));
//.......
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.w("Response ","Status line : "+ response.getStatusLine().toString());
buffer = EntityUtils.toString(response.getEntity()).getBytes();
I am using:
Log.d("log_response", response.getStatusLine().toString());
Related
I have a backend for my android app, which returns 404 on GET and json on POST. Now, I'm trying to do POST request using this snippet:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/api/login");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", "email#email.com"));
nameValuePairs.add(new BasicNameValuePair("password", "qwerty"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Server however receives GET request. With curl POST backend returns json as expected. But somehow httpPost sends GET(!) request. What could be the problem? What am I doing wrong?
Ok guys, answered my own question pretty quickly, may be helpful for others.
I replaced hostname with ip address, and it worked!
So i'm a web developer by trade but am making an app at the moment.
I've got a program on my PC which sends data from my PC to a database on my webhost.
What I'm after now, is to create an app that is able to download that data with a series of queries.
Are there any good resources around that would help me to develop some Java code, to connect to a server through my tablet when I'm out and about and download the information from my webhost when on a different wifi network?
Thanks chaps, any help is appreciated.
The way I handle it is that I just create a web page based on what I want to do. For example if I want to verify a login on an app I create a page that takes in a username and password.
On the device I just post the username and password values by using a HTTP post transaction.
Example:
public boolean LoginUser()
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("your URL comes here...");
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
DataCrypt crypt = new DataCrypt();
try
{
this.Cryptemail = crypt.bytesToHex(crypt.encrypt(this.Email));;
this.Cryptpass = crypt.bytesToHex(crypt.encrypt(this.Password));
}
catch (Exception e)
{
DebugLog.log(e.getMessage());
}
nameValuePairs.add(new BasicNameValuePair("Password", this.Cryptpass));
nameValuePairs.add(new BasicNameValuePair("Mail", this.Cryptemail));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
BasicHttpResponse response = (BasicHttpResponse) httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String response = EntityUtils.toString(entity);
return true;
}
catch (Exception e)
{
DebugLog.log(e.getMessage());
return false;
}
return false;
}
EDIT: So you can just make a page that takes in some parameters that you want to base your query on and return the result in some way (for example by XML).
Hope this helps you out! :)
I have been pen testing a random android app that uses POST method to send data to a remote server using HTTPS.
I have set up a proxy and am able to intercept the traffic, however the POST method appears to be encrypted and "url-encoded" .
What i want to know is .. is there a common encryption standard followed in such a scenario something like the Base64 or would it be so that the application uses a signature encryption mechanism internally which encrypts the data before it is sent through the POST method.
Any guidance would be really appreciated. Thanks in advance !
You can set encoding to whatever you like
UrlEncodedFormEntity(nameAndValuePairsGoHere,"encoding goes here");
Full example, credit: Source
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
I want to send the JSON text {} to a web service and read the response. How can I do this from android? What are the steps such as creating request object, setting content headers, etc.
My code is here
public void postData(String result,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(result.toString());
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
what mistake i have done plz correct me because it shows me an bad request error
but when i do post in poster it shows me status as Successfull 200 ok
I do this with
httppost.setHeader("Content-type", "application/json");
Also, the new HttpPost() takes the web service URL as argument.
In the try catch loop, I did this:
HttpPost post = new HttpPost(
"https://www.placeyoururlhere.com");
post.setHeader(HTTP.CONTENT_TYPE,"application/json" );
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("json", json));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
response = EntityUtils.toString(entity);
You can add your nameValurPairs according to how many fields you have.
Typically the JSON might become really huge, which I will then suggest gzipping it then sending, but if your JSON is fairly small and always the same size the above should work for you.
If it is a web service and not RestAPI call then, you can get the WSDL file from the server and use a SOAP Stub generator to do all the work of creating the Request objects and the networking code for you, for example WSClient++
If you wish to do it by yourself then things get a little tricky. Android doesn't come with SOAP library.
However, you can download 3rd party library here: http://code.google.com/p/ksoap2-android/
If you need help using it, you might find this thread helpful: How to call a .NET Webservice from Android using KSOAP2?
If its a REST-API Call like POST or GET to be more specific then its is very simple
Just pass a JSON Formatted String object in you function and use org.json package to parse the response string for you.
Hope this helps.
can anyone give me an idea of using web service using HTTP protocol.
Here is an example for "Executing a HTTP POST Request with HttpClient":
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "123"));
nameValuePairs.add(new BasicNameValuePair("username", "Paresh"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
We can use web services in our application to send and receive data from a remote server. Consider the case of an login section from a application where you need to pass username and password to the server for checking the whether the user is a valid user or not. In this case the username and password are attached with a url and send it to the remote server for validation and in response you get a value stating whether the user is a valid user or not. Usually the response will be either in XML format or JSON format from there we need to parse that response to get the necessary values. Check out the following example code in this I have created a class named "parsing" and it using the http protocol to receive a data.
public class parsing extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://services.digg.com/topics?appkey=http://example.com&type=json";
HttpPost post = new HttpPost(postURL);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
String response=EntityUtils.toString(resEntity);
response=response.trim();
Log.i("RESPONSE=",response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
See the response on the Logcat and do not for get to include <uses-permission android:name="android.permission.INTERNET" />
because we are fetching the data from the remote server which needs internet permission.