I have some services with the following header and I want to call these methods in Android application. I wrote the following code for calling service is correct but if I add charset=utf-8 to the header, I get 400 error code. I should send Persian character in some methods and without UTF-8, I get incorrect characters on the server-side. Anyway, Please send your suggestion to edit my code.
Another note: I work with PostMan and post Persian character to the service and it shows correct characters.
WCF Header method:
OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate = "Test")]
Android Code:
this.jsonStringer=params[0].toString();
HttpPost request = new HttpPost(uri);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
StringEntity msg = new StringEntity(jsonStringer);
msg.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
msg.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
request.setEntity(msg);
response = httpClient.execute(request);
When I add request.setHeader("Content-type", "application/json; charset=utf-8"); I get 400 error code!
Header parameters are by default UTF8 but if you are trying to pass your parameters by putting them in the Body, you should do as follow.
Assume you have stored your non utf8 string in value1. First convert your string to utf8 using URLEncoder then add it to your jsonObject and cast it as body.
Here it is a sample code but in Kotlin!
val jsonObject = JSONObject()
jsonObject.put(“param1”,val1)
val val1 = URLEncoder.encode(value1,”utf8”)
jsonObject.put(“param2”,val2) // and so on
val body = jsonObject.toString().toRequestBody(“application/json; charset=utf-8”.toMediaTypeOrNull())
Important Notice
Make sure you string is not urf8 because unless you are reading it from an ANSI txt file, they are Unicode and you do not need to convert them. If you don’t see the result as you should see on the server, that is another issue.
This may be caused by the difference between the header you set in the request and the header you set in the basicheader.You can set their content-type to the same format.This setting in Java can solve this problem,you can try it in your program.
public static void main(String args[]) throws ClientProtocolException, IOException {
String json="{\"user\":{\"Email\":\"123\",\"Name\":\"sdd\",\"Password\":\"sad\"}}";
CloseableHttpClient httpClient=HttpClientBuilder.create().build();
HttpPost request = new HttpPost("http://localhost:8012/ServiceModelSamples/service/web/user");
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json;charset=utf-8");
StringEntity msg = new StringEntity(json);
msg.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json;charset=utf-8"));
msg.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
request.setEntity(msg);
HttpResponse response = httpClient.execute(request);
System.out.println(response);
}
Related
I'm creating an android application in which I would like to send some values to the server and in response the server gives me a json response. The values I pass through is of Json post method type.
I would like to know how can I pass the following values to the Json post url:
{
"CPSProfileInfo":
{
"cpsName": "auto",
"userId": "0",
"cpsAddress": "0#0India",
"searchLimit": "10#0",
"searchFlag": "0"
}
}
throught my application so far, I've been using
params.put("cpsName","auto");
But I don't know how to proceed with this type as I don't know how to send the value for CPSProfileInfo
Kindly help me solving this issue!!!
You can go through the tutorial android-json-parsing-tutorial...
First know how json format looks!
To send Json to server, you can try my code:
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
HttpClient httpclient = new DefaultHttpClient(myParams);
HttpPost httppost = new HttpPost("*your server addresss and query*");
httppost.setHeader("Content-type", "application/json");
//if needed for authorization:
httppost.setHeader("Authorization", "Bearer " + "*Your string token retrieved from server*");
StringEntity se = new StringEntity("*your json here*");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
If you have any questions, please ask.
Checkout Retrofit, it is an awesome networking library by Square.
When posting in retrofit you can just create a class for the object:
#POST("/users/new")
void createUser(#Body User user, Callback<User> cb);
This is posting to the url 'yourdefinedapi.com/users/new with an User object, which is just a POJO object :)
See detailed instructions here: http://square.github.io/retrofit/
I am working with JSON Restful web serivces where I have to pass JSON object in the Service URL. I have created the JSON object successfully but getting exception when my URL created the HTTP connection with the SERVER.
Below I have mention my URL:
http://72.5.167.50:8084/UpdateProfileInfo?{"ProfileEditId":"917","ContactsEmail":[{"Email":"dsfs","ContactId":""}],"ContactsPhone":[{"CountryId":"+1","Type":"2","Phone":"345345"}],"ProfileId":"290","LastName":"demo","GroupId":"1212","Title":"sdf","City":"dsf","TemplateId":"1212","State":"dsf","AuthCode":"9bcc6f63-2050-4c5b-ba44-b8103fbc377a","Address":"sdf","FirstName":"demo","ContactId":"","Zip":"23","Company":"tv"}
Getting java.lang.IllegalArgumentException: Illegal character in query in code :
int TIMEOUT_MILLISEC = 100000; // 1000 milisec = 1 seconds
int SOCKET_TIMEOUT_MILISEC = 120000; // 2 minutes
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, SOCKET_TIMEOUT_MILISEC);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost request = new HttpPost(url);
HttpResponse response = client.execute(request);
responseString = request(response);
Please suggest me If I am doing something wrong with my URL.
*EDITED:*Tried with a key still getting Exeception:
http://72.5.167.50:8084/UpdateProfileInfo?profileinof={"ProfileEditId":"917","ContactsEmail":[{"Email":"sdf","ContactId":""}],"ContactsPhone":[{"CountryId":"+1","Type":"2","Phone":"345345345"}],"ProfileId":"290","LastName":"demo","GroupId":"1212","Title":"dsf","City":"dsf","TemplateId":"1212","State":"dsf","AuthCode":"d968273a-0110-461b-8ecf-3f9c456d17ac","Address":"dsf","FirstName":"demo","ContactId":"","Zip":"23","Company":"tv"}
There is different format of HTTP request that we needed to make for this kind of REQUEST.
I have mention my code below for this.
public JSONObject getJSONObject(){
return jsonObj;
}
ABove method returns me a JSON String which is passed in the below method.
public static HttpResponse makeRequest(String url) throws Exception
{
//instantiates httpclient to make request
DefaultHttpClient httpclient = new DefaultHttpClient();
//url with the post data
HttpPost httpost = new HttpPost(url);
//convert parameters into JSON object
JSONObject holder = getJSONObject();
//passes the results to a string builder/entity
StringEntity se = new StringEntity(holder.toString());
//sets the post request as the resulting string
httpost.setEntity(se);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
//Handles what is returned from the page
ResponseHandler responseHandler = new BasicResponseHandler();
return httpclient.execute(httpost, responseHandler);
}
Stack post helped me for doing this task...!!!
The IP is not correct.
IP is formed with 4 bytes. Every byte is a value from 0 to 255, can't be 7 thousand.
http://7232.25.1617.50:1084
Edit: Okay, you edited your question. You're sending a JSON as parameter. But this parameter has no "key".
Should be:
/UpdateProfileInfo?info={"ProfileEditId":"917",[.......]
Edit: I think this should be like this:
/UpdateProfileInfo?info="{'ProfileEditId':'917',[.......]}"
Notice that the value is surrounded by ", and the inner " are replaced now by '
Probably the issue is that you are trying to POST a JSON object as an url param.
If it really has to be an url param, that it has to be urlencoded.
If it rather should be a normal POST request, I's suggest to use a high level helper:
new RESTClient2(ctx).post("http://72.5.167.50:8084", jsonObject);
I can see a need to work with POJOs , converting them to JSON strings and conveying that string info over HTTP. There are lots of good android/java/apache/volley type libs that permit that.
However, i do not understand, in fact i disagree with your requirement to use GET and the URL parms for transport of your JSON string?
Its really easy to do the following:
POJO -> to JSON -> toString -> to http.string.entity -> POST
Why not re-examine your architecture and consider using POST not GET.
Then its easy , 2 step:
see example "request.setEntity( ... "
your code will look like this:
httpPost.setEntity(new StringEntity(pojo.toJSON().toString()));
I use HttpClient in android to send post request:
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(hostNameCollection);
StringEntity se = new StringEntity(jsonObj.toString());
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
request.setEntity(se);
HttpResponse response = client.execute(request);
Log.v("HttpLogClient.logJSONObject", "wyslano JSON");
and I'dont know how I can receive JSON object on my Java EE servlet.
you need to read the response body text, then parse as JSON,
String result = EntityUtils.toString(response.getEntity());
JSONObject jo = new JSONObject(result);
read the body of the http post ( server-side ) by getting the a stream object on the body and then reading it.
Once youve read it , convert the bytes to chars and that will be json which you can use to build a json object like a jsonNode using 'jackson' libs.
If you are using plain servlets the json stream is located in the body of the HttpServletRequest : request.getReader() or request.getInputStream();
To make things easier you could use a library handling databinding for you.
Have a look at Genson http://code.google.com/p/genson/.
YouClass object = new Genson().deserialize(request.getReader(), YourClass.class);
// or to a plain map
Map<String, Object> map = genson.deserialize(request.getReader(), Map.class);
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.
I am trying to post a JSON-object to a REST webservice from an Android application. Everything works fine until I add special characters like å, ä, ö.
JSONObject absenceObject = new JSONObject();
absenceObject.put(INFO_DESCRIPTION, "åka pendeltåg");
StringEntity entity = new StringEntity(absenceObject.toString());
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json";character);
httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
HttpResponse response = httpclient.execute(httpPost);
If I print absenceObject.toString() and copy the result in to a regular rest client it works fine as well.
Try specifying the desired charset in the StringEntity constructor:
StringEntity entity = new StringEntity(absenceObject.toString(), "UTF-8");
If you control both ends of the pipe, you can encode the REST text as shown here Encoding/decoding REST path parameters
Re: Mark's response
Try specifying the desired charset in the StringEntity constructor:
StringEntity entity = new StringEntity(absenceObject.toString(), "UTF-8");
Note that setting charset after the constructor didn't work for me i.e.
entity.setContentEncoding("UTF-8");
I had to do as Mark said and set it in the constructor.
Michael
byte[] buf = body.getBytes(HTTP.UTF_8);
wr.write(buf, 0, buf.length);
Try this it will work.