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.
Related
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.
When sending the POST request using UrlEncodedFormEntity which takes List as input parameter along with the key, my request gets converted in the form of [key={json}] .
But the request i want to send should be in the form of key={json} , i.e not as List.
So, is there any alternative for the given method when using POST?
notes: webservice is working fine , and since it is json ,i cannot use Soap .
i ve tested it using POSTman and webservices are WCF(if thats of any use..)
if any code is required , please mention it.
Thanks in advance.
Edit code:
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(URL);
List<NameValuePair> value=new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("data",string));
//here it passes as List and here is where i want an alternate method
// by which i can send parameter as JSONobject
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(value);
request.setEntity(entity);
HttpResponse response = client.execute(request);
HttpEntity entity2 = response.getEntity();
if(entity2.getContentLength() != 0) {
Reader tapReader = new InputStreamReader(response.getEntity().getContent());
char[] buffer = new char[(int) response.getEntity().getContentLength()];
tapReader.read(buffer);
tapReader.close();
JSONObject tapJsonObj = new JSONObject(buffer);
I am writing an application in android and i am sending a json object to a java servlet.
This is the android code:
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
JSONObject jsonObjectToPass = returnJsonStringObject();
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("jsonGPSParameter",jsonObjectToPass.toString()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
entity.setContentEncoding(HTTP.UTF_8);
entity.setContentType("application/json");
post.setHeader("Content-type", "application/json");
post.setEntity(entity);
response = httpClient.execute(post);
This is the java servlet code
request.getParameter("jsonGPSParameter");
The problem is that the getParameter() method return null.
Im not be able to spot the problem.
If someoane can help me it would be a great help.
Thanks
For the code to work proper i have to remove the next to lines from android code:
entity.setContentType("application/json");
post.setHeader("Content-type", "application/json");
This is the code done in C# for posting an XML Document Element
XmlString = #"<WOITEMS><WOITEM ACTION='I'>" + TransData + "</WOITEM></WOITEMS>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(XmlString);
saveRegisterItems(xmlDoc.DocumentElement);
saveRegisterItems is a WCF service method which receives a Document Element as it's parameter. How can I do that in Android using HttpPOST? I tried the below code. But, it doesn't work.
HttpResponse response = null;
String myUrl = "http://"+Constants.strURL+"/ServiceOrders.svc/SaveRegisterItems";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(myUrl);
StringEntity se = new StringEntity(XmlString, HTTP.UTF_8);
se.setContentType("text/xml");
httpPost.setHeader("Content-Type", "application/soap+xml;charset=UTF-8");
httpPost.setEntity(se);
I get response.getStatusLine() as "HTTP/1.1 200 OK" but, it's not updated in the server. I think, passing a XML Document Element will do it. Please Help
I got the solution when I changed the second parameter of httpPost.setHeader() method. It should like this.
httpPost.setHeader("Content-Type", "application/xml;charset=UTF-8");
I got proper response by giving EntityUtils.toString(entity).
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.