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);
}
Related
I'm using ASP Web API web service which is hosted on SmarterAsp.net to get data in Json format to use them in my android application, when I use Wifi everything works fine and the Json is received correctly but when I use mobile data I get com.google.gson.JsonSyntaxException while parsing the Json received, I checked the received Json string with the debugger and it was malformed and here is what i received :
��������������RMo�#�+՞)��Sڦ9TjeU�)�aX�x\��Ah"�{b�����̾y3OL�G�Y�İ�u²"���r'��J V�#�����(���
���(N9*4MĜ���Fר��m+
���:�7[�/$3��z����c�%q*Ha�OA|�x~������G�8���"?,�4���(��y���N��j�L%���?B
�?S8�lp���(G�rgH�����P�b9����+5��<�n����w_i�G-,��_؋��uz�K;��|�i������� ��|6s����V[J�<�%3���X�������
And here is the method I'm using in android to send and receive data from the ASP Web API web service :
public String PostObject(String url, Object obj) throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
StringEntity stringEntity = new StringEntity(new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create().toJson(obj));
httpPost.setEntity(stringEntity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Accept-Encoding", "gzip");
HttpResponse httpResponse = client.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String rep = EntityUtils.toString(httpEntity);
return rep;
}
It is not malformed. You are accepting gzip compressed data by declaring ("Accept-Encoding", "gzip") in the header.
You can either remove the compression or decompress the data and then use it.
On how to decompress
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)
I'm working on a project which requires me to send a post request to
http://sagecell.sagemath.org/kernel (just a post, no data)along with two extra headers,
Accept-Encoding:identity and accepted_tos:true.
This works fine if using the default httpClient like so:
httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost();
String url = UrlUtils.getKernelURL();
httpPost.setURI(URI.create(url));
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair(HEADER_ACCEPT_ENCODING,VALUE_IDENTITY));
postParameters.add(new BasicNameValuePair(HEADER_TOS,"true"));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
webSocketResponse = gson.fromJson(new InputStreamReader(inputStream), WebSocketResponse.class);
inputStream.close();
However if I want to use the same thing using the OkHttpClient, it gives me a 403 error:
httpClient = new OkHttpClient();
public static final MediaType jsonMediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(jsonMediaType, "");
Request request = new Request.Builder()
.addHeader(HEADER_ACCEPT_ENCODING, VALUE_IDENTITY)
.addHeader(HEADER_TOS, "true")
.url(url)
.post(body) //I've tried null here as well
.build();
Response response = httpClient.newCall(request).execute();
Log.i(TAG,"STATUS CODE"+response.code()); //This is 403
This is the same story with libraries like Ion and even HttpUrlConnection, only the Apache Client seems to work.
Any answers as to why this isn't working would be appreciated.
error 403 means its forbidden by the server.
And in the first case(while using default httpclient ) you are not adding header, you are just adding a name-value pair to the entity.
to add a header you should use
httpPost.addHeader("key","value");
Your request body is empty. You should provide a form-encoded request body, or a JSON request body, and the corresponding content type.
If you want, MimeCraft will build you a form-encoded request body, and Gson will do JSON.
in my app i need to post data to an url to register a new user. Here is the url
http://myurl.com/user.php? email=[EMAIL]&username=[USERNAME]&password[PASS]&img_url=[IMG]
If I do that correctly I should get this message:
{"success":true,"error":null}
or if not {"success":false,"error":"parameters"}
Can somebody guide me through this and tell me how can I do it.
first :
you need to perform all network tasks in an Async thread using:
public class PostData extends AsyncTask<String, Void, String>{
{
#Override
protected String doInBackground(String... params) {
//put all your network code here
}
Second:
create your http request:
i am assuming email, username and IMG as variables over here.
String server ="http://myurl.com/user.php? email=[" + EMAIL + "]&username=[" + USERNAME + "]&password[" + PASS + "]&img_url=["+IMG + "]";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(server);
//httppost.setHeader("Accept", "application/json");
httppost.setHeader("Accept", "application/x-www-form-urlencoded");
//httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
third:
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("JSONdata", Object));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
try {
HttpResponse response =httpclient.execute(httppost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Now simple query your response handler i.e. response in this case.
Don't forget to add INTERNET permission in your androidManifest.xml
Hope this helps!
Use a HTTP client class, and format your URL via a specific URI constructor. Create a HTTP post, optionally set the entity, headers, etc, execute the post via the client, receive a HTTP response, pull the entity out of the response and process it.
EDIT for example:
HttpClient httpclient = new DefaultHttpClient();
URI uri = new URI("http",
"www.google.com", // connecting to IP
"subpath", // and the "path" of what we want
"a=5&b=6", // query
null); // no fragment
HttpPost httppost = new HttpPost(uri.toASCIIString);
// have a body ?
// post.setEntity(new StringEntity(JSONObj.toString()));
// post.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
Reader r = new InputStreamReader(entity.getContent());
// Do something with the data in the reader.
I just need to send request to webservice via normal HTTP POST inorder to get response.I passed required parameter on body well.While i run it.,i got "Cannot process the message because the content type 'text/json' was not the expected type 'application/soap+msbin1'." error.When i made research over this.,due to "Web Service required the request to have a specific Content-Type, namely "application/soap+msbin1".When i replaced expected content type.,i got Bad Request error.I donno how to recover from that.
My code:
...
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler <String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("My URL");
postMethod.setHeader( "Content-Type", "text/json");
postMethod.setHeader( "Cache-Control", "no-cache");
JSONObject json = new JSONObject();
json.put("userName", "My Username");
json.put("password", "My Password");
json.put("isPersistent",false);
postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
HttpResponse response = httpClient.execute(postMethod);
...
It looks like you are trying to call WCF SOAP service. That service expects correct SOAP communication (= no JSON) and moreover it uses MS binary message encoding of SOAP messages (that is what content type describes) is not interoperable so I doubt you will be able to use it on Android device (unless you find implementation of that encoding for Java / Android).
HttpPost request = new HttpPost(url);
StringEntity entity = new StringEntity(json.toString());
entity.setContentType("application/json;charset=UTF-8"); entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
request.setHeader("Accept", "application/json");
request.setEntity(entity);
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
response = httpClient.execute(request);
}
Try using something like this. it worked for me.
Thanks.
N_JOY.