I use the following code to send data to my server:
public InputStream getStreamFromConnection(String url, List<NameValuePair> params) throws ClientProtocolException, IOException {
if(ConnectionDetector.isConnectedToInternet(this.context)) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
return httpEntity.getContent();
} else {
return null;
}
}
When i now have a message in my params which looks like that:
The leadership earned 1000$ during the last years.
The server receives:
The leadership earned 1000
And all of the messages are cut exactly at the index of any special character.
And even more. if somone writes a message with a smile like:
:)
This arrives at the server
??
How can i send the special characters and smielies to the server?
It sounds like you just have to encode your URL before you execute a request with it.
Try encoding your URL like this:
String encodedUrl = URLEncodedUtils.format(urlWithParameters, "utf-8");
Do you have before your special characters this \\?
because without it the server won't understand it.
(Sorry I couldn't leave a comment due to reputation)
Related
I am working on web service which send some parameter by post request.
But on the server side i always get wrong string.
As an example if i send "testing éra l'university" at server side its
Output is = "testing ?ra l'university"
It added ? in special character of french word.
This is my async task code
parameter.add(new BasicNameValuePair("diplome_nom", diplome_nom));
parameter.add(new BasicNameValuePair("ecole_nom", current_post));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity( parameter, "UTF-8" ));
HttpResponse httpResponse = httpClient.execute(httpPost);
and Jersey server as
#POST
#Produces("application/json")
#Path("/v1/formation")
public Response UpdateUserFormation (
#FormParam("diplome_nom") String diplome_nom, #FormParam("ecole_nom") String ecole_nom ...)
{
String decodedValue1 = URLDecoder.decode(ecole_nom, "UTF-8");
System.out.println("ecole_nom after decoding => " + decodedValue1);
}
Here is how I use POST and it works:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
And I didnt know how to use PUT, so I got this code and I changed every "Post" to "Put"
but I dont think it works:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPut httpPut = new HttpPut(url);
httpPut.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPut);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
When I try updating a user's account using this implementation ot PUT I get errors from the server. - "No session. Unauthorized."
When I use Chrome's postman with the same parameters, I get no problem, so I think my PUT implementation doesnt work.
You need to use the same DefaultHttpClient to make all the calls, because your session information is stored in the instance object.
If you need to use different instances, you may be able to do that getting the cookies from the login request and add them in the next requests using getCookieStore/setCookieStore.
I need to use httpclient to connect to a webpage (Apache) running PHP scripts which is protected with .htaccess authentication.
I've been reading questions and answers (in here and other places) for an hour now, and none of the sultions is working for me. Either the methods people are using in classes like Base64.java does not exist, or the parameters are wrong.
I'm connecting to normal (non-protected webpages like this):
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
nameValuePairs.add(new BasicNameValuePair("date", cDate));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
But this, naturally, doesn't help when the page is protected. So how can I, in the easiest way, pass my username and password to the connection?
You can get a Base64 here: http://iharder.sourceforge.net/current/java/base64/.
I usually do something like following for authentication:
StringBuilder authentication = new StringBuilder().append("dogT4g").append(":").append("petTheDog5");
String result = Base64.encodeBytes(authentication.toString().getBytes());
httppost.setHeader("Authorization", "Basic " + result);
Hope that solves your problem.
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.
I needed to send some XML to a webservices and I was able to do it with a normal StringEntity because it was just text but now I need to attach an image to it as well. I tried doing it with a MultipartEntity but I couldn't get it working with just the XML.
// Working
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost doc = new HttpPost("http://mywebservices.com");
HttpEntity entity = new StringEntity(writer.toString());
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity responseEntity = response.getEntity();
// not working
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost doc = new HttpPost("http://mywebservices.com");
// no difference when removing the BROWSER_COMPATIBLE
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("xml", new StringBody(writer.toString()));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity responseEntity = response.getEntity();
And is there a way I could see the MIME that is being send?
You simply forgot:
httppost.setEntity(entity);
By the way, it's probably good form to set the Content-Type of your parts, e.g.:
entity.addPart("xml", new StringBody(writer.toString(),"application/xml",Charset.forName("UTF-8")));
As far as seeing what's being sent, see http://hc.apache.org/httpcomponents-client-ga/logging.html (especially "wire logging") for the HttpClient logging features, and
this question for how to get it working on Android.
Another way to see what's being sent is to set up your own "server" to receive the request. You can do this on a Unix-like system with netcat. The command-line
nc -l 1234
starts a server listening on port 1234, and will echo whatever is received.
If that "server" is on a machine 10.1.2.3, you can just use a new HttpPost("http://10.1.2.3:1234") to send the message there.
I have a similar problem but I'm sending the multipart with user/pass to a acegi security system, it works with this:
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
But not with this:
try {
for (NameValuePair param : params) {
multientity.addPart(param.getName(), new StringBody(param.getValue(), Charset.forName(encoding))));
}
request.setEntity(multientity);
}