HttpServletRequest get no parameters from my httppost - android

I have just a curiosity question. I have an HttpPost request in Android that looks something like this:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(getString(R.string.url));
//This code does not work
HttpParams params = new BasicHttpParams();
params.setParameter("type", "20");
post.setParams(params);
try {
HttpResponse response = client.execute(post);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
On my server side, I have a servlet that listens for requests and parses the parameters:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Enumeration en = request.getParameterNames();
while (en.hasMoreElements()){
System.out.println(en.nextElement());
}
}
When I execute this code, the servlet does not see any parameters at all. But if I replace the whole "parameter" chunk with this code:
//This code works
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("type", "20"));
try {
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
My servlet can parse parameters. It's not a problem, I'm just going to use the entity but my question is, why can't my servlet getthe parameters from the first code chunk? What's wrong with setParams? Why can the servlet see parameters if I make them an entity?

In HTML when we have something like "http://host/path?user=uname&passwd=pass", we call the part (user=uname&passwd=pass) after the question mark "form data".The "form data" can be attached to the end of the URL after a question mark (as above), for GET requests, or sent to the server on a separate line, for POST requests.The "form data" are split to parameters. The parameters are separated by & when we use GET.
In our case the HttpPost and HttpGet classes extend the AbstractHttpMessage which implements the setParams method. This method is same for GET and POST but does the job only for GET! In the case of GET the parameters are put in the URL. In the case of POST you need to set the entity for the parameters to be on a "separate line".
On the server side when using servlets the getParameters is clever enough to find the parameters for GET and POST.
Thats why on the server side we do not need to change the code for getting the parameters!
Hope I helped!

Related

Is there any way to create a mini-proxy for http on android?

I am working on a HttpClient that posts something to a website. The client looks something like this (based on this link):
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));
// 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
}
}
What I want to do now is to create a small proxy service (a VERY simple one) that runs on the same android device and listens for the outgoing HTTP connexions and modifies the POST ( for example change the "id": "12345" into "54321", just for testing purposes), and then pass the HttpRequest to the actual website. How cand I do something like that? I've been googling around but found nothing that could give me an idea how to do it(like a tutorial or something). Can anybody give me an idea of how to do that?
You do not need to write code to achieve this. Instead of writing your own proxy and since you only need it to test you application, you can use the mitmproxy which is a man-in-the-middle proxy (based on your description that is what you want to achieve). Follow this tutorial to set up your PC as the proxy and the device as your client.
http://blog.philippheckel.com/2013/07/01/how-to-use-mitmproxy-to-read-and-modify-https-traffic-of-your-phone/

android webview working with json post and response

I have a sample url like this:
http://www.sample.com/mobile.cgi?action=login&json_request={"user":{"name":"a","pass":"123","gender":"m","age":"25"}}
I can basically use webview.loadurl to send data to the server, but the point is...I cant get response from the server. I'm new to json. Is there any way that I can post json using the regular way? like HttpPostmaybe? and be able to get response properly.
Thanks!!
If you just wish to post JSON using HTTP and get a response back, there are many posts of stackoverflow which will help you answer that. Check How to send POST request in JSON using HTTPClient? question. I think this question answers what you are trying to say. Hope this helps you. If you have any specific concern you can always comment.
Update
As you said that you already have keys and corresponding values in addition to URL.
The first step would be to create a JSON Object. Convert it to string and then you can send it using HTTPClient and get the response back. Something like:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/");
try {
// Add your data
JSONObject user = new JSONObject();
user.put("Name", "a");
user.put("pass", "123");
// Create StringEntity
StringEntity se = new StringEntity( user.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
// 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
}
You can check links like this to see further exact format. I wanted to tell you the method as to how you can proceed. Hope this helps.

Can't finally perform HTTP POST request

I work on my first Android application and I have some great problems with trying to make HTTP POST request and receive response. These are few facts:
I have INTERNET permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
I tried many solutions. Solutions with URLConnection or HttpURLConnection don't work because they return empty string. Solution with HttpClient and HttpPost fails on execute() - I was googling for an hour but didn't find out how to fix that.
There is internet connection. But I don't know how to fix my problem and finally to send HTTP POST request.
upd: e.g. this code makes my program crash:
public static APIResponse getResponse(String action, Map<String, String> params) throws IOException {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://google.com");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
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
}
return null;
}
upd 2: it works on my phone but doesn't work on emulator! how to fix that behaviour on emulator?
upd 3: fixed.
Look at the example for HTTP Post
You should also employ fiddler2 to help debug your HTTP messages.
Also please note that you are not catching all exceptions properly ... you can add a generic catch statement at the end to prevent your app from crashing and help you figure out where the problem lies. Could be a timeout or similar.

HTTP Post OK, how to display the response?

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());

Web Service using HTTP Protocol in Android

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.

Categories

Resources