I am sending data from android client to a server
httpPost.setEntity("Some String");
or
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
I want to retrieve this string or namevaluepairs or a hashmap.
I want to use a servlet instead of php scripting. I had looked at all methods of HttpRequest but missing something.
I am running the app in emulator with a tomcat local host and with 10.0.2.2 ip from emulator.
please provide a sample for such servlet. Thanks in advance
In your servlet call request.getParameter("parameterName") to retrieve the parameters sent from your Android device. The parameter name is the same name you use in your name/value pairs.
Assuming you are using a POST (if not, override doGet instead), your servlet should look like this:
public class MyServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String value = request.getParameter("parameterName");
... more
}
}
Related
I am using an API that is out of my control, as well having joined a development team recently that is using Retrofit1.
I am unable to send the request to the server in the format required, as the server requires multipart form data Body in the following format:
Uniqueidentifier:FileName.jpg:ReroutServerIP:Base64EncodedDocString.
I have tried many different techniques in order to accomplish this task but I cannot find any working method to do this. The server tells me that the message format not supported. Here is my current code (with the url stripped out). Please could someone assist?
#POST("URL")
public Response post_SendData(#Header("Content-Type") String ContentType, #Body String body);
In order to achieve the desired result, I can use postman with no headers and post a file from my system using the form-data post method. In the working postman post, the Key is the formatted string mentioned above and the value is a file selected from my desktop. Please see below for postman (edited to remove urls).
Postman
Thanks a lot guys.
If you want to send a file to the server :
public void uploadPictureRetrofit(File file, Callback<YourObject> response) {
// this will build full path of API url where we want to send data.
RestAdapter restAdapter = new RestAdapter
.Builder()
.setEndpoint(YOUR_BASE_URL)
.setConverter(new SimpleXMLConverter()) // if the response is an xml
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
// SubmitAPI is name of our interface which will send data to server.
SendMediaApiInterface api = restAdapter.
create(SendMediaApiInterface.class);
TypedFile typedFile = new TypedFile(MULTIPART_FORM_DATA, file);
api.sendImage(typedFile, response);
}
And this is the interface SendMediaApiInterface :
public interface SendMediaApiInterface {
#Multipart
#POST("url")
void sendImage(#Part("here_is_the_attribute_name_in_webservice") TypedFile attachments, Callback<YourObject> response);}
I'm sending post content to a server from android.
The problem is that the data at the server arrives wrong, with encoding problems, for example "{" arrives as "%7B%".
This is the code from android:
RequestParams params = new RequestParams();
params.put("alta", "{s}");
String ruta = "http://www.something.com/receive";
client.post(ruta, params,
new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
}
}
The server part is just receiving this data, like:
$data = $this->request->data;
$data =file_get_contents('php://input');
This issue is not directly related to text encoding per se.
As can be seen from the docs for RequestParams, text values are directly included in the url. As all text that is included in URLs has to be encoded to only include characters that are allowed in URLs (ASCII), text is url encoded.
AsyncHttpClient automatically does that encoding in the background, so you receive the strings in encoded form on the php side.
In order to get the original text you sent, you can use the rawurldecode() or urldecode() function on the php side to decode the encoded string you receive.
You need to use URLEncoder.encode(...) the the data part of you request.
At the server URL decode it.
You should be fine.
on the server side i am doing this and have to send three strings from this class
to the client side in android application
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
name1 = getParameter(req, "name");
phone1 = getParameter(req, "phone");
dob1 = getParameter(req, "dob");
String regId = getParameter(req, PARAMETER_REG_ID);
resp.setContentType("text/html");
Datastore.register(regId);
Datastore.register_name(name1);
Datastore.registerPhone(phone1);
Datastore.registerDob(dob1);
}
And On The Client Side I have to Recieve it
Actually i was doing it to get responses from server to client it has relay simple solution what you want to send from server to client side if you have post method in the do post method u have to make some output stream and what ever you write on the stream you can get easily by reading that output stream
yes u can use this way on servlet response
resp.setHeader(java.lang.String name, java.lang.String value)
and at Android end you can get the value from response
String value =response.getHeaders(name);
I hope u will get into the way i told u .....
Your question is not clear ...
Please edit your question and explain in detail
What I have understood is: You want to send some messages / parameters from your back end Server to the Mobile device.
If this is what you need, then have a look at the Google Cloud Messaging : http://developer.android.com/google/gcm/index.html which is designed specifically for this.
i've got a problem do a http post on android with german "umlaute" äöü. I am passing a json object to the method below and execute the returned ClientResource with post and the request entity in the returned client response. When I want to post something like { "foo":"bär" } the HttpClient sends something like { "foo":"b√§r" }.
Don't know why. What am I doing wrong.
public static ClientResource newPostRequest(Context context, String urn,
JSONObject form) throws MissingAccessTokenException {
ClientResource resource = new ClientResource(uri + urn);
StringRepresentation sr = new StringRepresentation(form.toString());
sr.setMediaType(MediaType.APPLICATION_JSON);
resource.getRequest().setEntity(sr);
return resource;
}
Update
I used the default android http client (which is a apache http client I believe) and got the same error. So the problem might be located here. I try to implement another json parser (currently gson) and (if possible) another http client. Be back later...
Update
Gson is not the problem. I added a json String to the StringRepresentation and nothing changed.
ANSWER
Well that's an odd one. Maybe someone can clear this for me. I always asked myself, why √§ where used and I figured out that translating the utf-8 ä leads to √§. Obviously my android phone did not use macroman, but my mac did. I therefor changed the text file encoding in eclipse, restarted eclipse and the tomcat server and it worked. Still the TCP/IP Monitor in eclipse uses mac roman which looks still wrong. It was thereby a problem with my server, not with the restlet client on android. I just couldn't see it because the TCP/IP Monitor encoded everything in macroman.
did you try calling setCharacterSet(...) on your StringRepresentation? e.g.,
StringRepresentation sr = new StringRepresentation(form.toString());
sr.setCharacterSet(CharacterSet.UTF_8);
I need to upload an image to a remote PHP server which expects the following parameters in HTTPPOST:
*$_POST['title']*
*$_POST['caption']*
*$_FILES['fileatt']*
Most of the internet searches suggested either :
Download the following classes and trying MultiPartEntity to send the request:
apache-mime4j-0.5.jar
httpclient-4.0-beta2.jar
httpcore-4.0-beta3.jar
httpmime-4.0-beta2.jar
OR
Use URLconnection and handle multipart data myself.
Btw, I am keen on using HttpClient class rather than java.net(or is it android.net) classes. Eventually, I downloaded the Multipart classes from the Android source code and used them in my project instead.
Though this can be done by any of the above mentioned methods, I'd like to make sure if these are the only ways to achieve the said objective. I skimmed through the documentation and found a FileEntity class but I could not get it to work.
What is the correct way to get this done in an Android application?
Thanks.
The Android source seems to come with an internal multipart helper library. See this post. At a quick glance, it's better documented than plenty of public APIs (cough cough, SoundPool, cough cough), so it should be a pretty good place to start, or possibly fine to just use a drop-in solution.
Maybe this post on the official Android group helps. The guy is using mime4j.
Another helpful resource could be this example in the Pro Android book.
I do exactly that to interact with an image hosting server (implemented also in php) that expects parameters as if they were posted from an html page.
I build a List<NameValuePair> of my keys and values something like this:
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair(key1, value1));
params.add(new BasicNameValuePair(key2, value2));
and then I pass it to my http helper class that sets the HttpEntity property of my HttpPost request. Here's the method straight out of my helper class:
public static HttpResponse Post(String url, List<NameValuePair> params, Context context)
{
HttpResponse response = null;
try
{
HttpPost request = new HttpPost();
request.setURI(new URI(url));
if(params != null)
request.setEntity(new UrlEncodedFormEntity(params));
HttpClient client = ((ApplicationEx)context.getApplicationContext()).getHttpClient();
response = client.execute(request);
}
catch(Exception ex)
{
// log, etc
}
return response;
}