In my Android application, i'm using ksoap2 library for consuming a soap ( & .net) webservice. It works correctly but it's very slow (for parsing, controls, loops and Base64ToBinary processes). I want to parse it more fast. Is it possible to parse it without using ksoap2? Any ideas?
Thanks for your recommendations.
What do you mean slow? It does a http request and then parses the response. You have to do this in an async task. Memory usage will depend on the response you get. Maybe you are requesting way too much. See the wiki on how to debug!
I have another problem with KSoap2. Unfortunately, ksoap2 library is not working with my webservices. So at last, I have done with default http post.
I hope this will help for someone in future.
private String makeHttpRequest(){
try{
String request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://tempuri.org/\">"
+"<SOAP-ENV:Body>"
+ "<ns1:Connect>"
+ "<ns1:lstr_Login>xxxxx</ns1:lstr_Login>"
+"</ns1:Connect>"
+"</SOAP-ENV:Body>"
+"</SOAP-ENV:Envelope>";
String soapAction = "http://tempuri.org/Connect"; //this would be your soapAction from wsdl
StringEntity se = new StringEntity(request, HTTP.UTF_8);
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(new URI("http://xxxxxxxx.com/Storefront.asmx"));
httpPost.addHeader("Content-Type", "text/xml; charset=utf-8");
httpPost.addHeader("SOAPAction", soapAction);
httpPost.setEntity(se);
HttpResponse response = client.execute(httpPost);
int responseStatusCode = response.getStatusLine().getStatusCode();
Log.d(TAG, "HTTP Status code:"+responseStatusCode);
if(responseStatusCode>=200 && responseStatusCode<300){
//we got the success response from server. Now retrieve the value and go for usage.
String responseStr = EntityUtils.toString(response.getEntity());
//use this responseStr to parse with pullparsers or any
Log.d("Response", "Response:: "+ responseStr);
return responseStr;
}
}catch(Exception e){
//Write the proper catch blocks for exceptions
Log.e("Response Exception" , e.getMessage()+"",e);
}
return null;
}
Related
In my android application I try to send a json object to a distant server, when I run it I get an error in httpclient.execute(httpPost)
This is a part of my code.
public static String GET(String url , JSONObject js){
try {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Authorization", "Basic **********");
httpPost.setEntity(new StringEntity(js.toString()));
HttpClient httpclient = new DefaultHttpClient();
httpclient.execute(httpPost);
} catch (Exception e) {
Log.i("Console", "Error");
}
Any help please.
I guess your Problem is, that you try to run your Network Request from your Main Thread.
I would discourage you to use the Apache HTTP Client at all.
It became deprecated for Marshmallow, see here
Maybe try OkHttp. It offers you the possibility to run a request asynchronously.
I am trying to get an android app to interact with a server in Django.
The app is trying to POST "json" data to Django. However, I am unable to receive the object on the Django end.
The value of request.POST is <QueryDict: {}> although the data sent isn't blank. Following is the code snippet for POST request from android.
public static String POST(String url,JSONObject obj){
InputStream inputStream = null;
String result = "";
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = obj.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type","application/json");
HttpResponse httpResponse = httpClient.execute((HttpUriRequest)httpPost);
inputStream = httpResponse.getEntity().getContent();
if(inputStream!=null){
result = convertInputStreamToString(inputStream);
}else{
result = "Did not work!";
}
}catch(Exception e){
}
return result;
}
EDIT:
Earlier, I was getting CSRF error and handled it this way (I haven't worked with Django enough to know if this is correct way to handle CSRF error)
#csrf_exempt
def search(request):
logger.debug(request.POST)
"""Code for JSON object processing"""
Any help with rectifying the problem would be highly appreciated.
OK I'm not very fluent in java but it seems to me that your request is well formed.
I think the issue is that you are sending the data as a json string instead of as if it was a raw form. When you do it this way, the data is not displayed in request.POST but in request.body as what it is: a json string, not form-like data.
So I think you have to take one of these ways:
send the data from the Android app as a form (not json-like). This way you'll see it in request.POST or
translate request.body into a dict and work with it instead of request.POST
Hope this helps! :)
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 have a RESTful WCF service and one of its methods use an Object as parameter
[WebInvoke(UriTemplate = "save", Method = "POST", RequestFormat = WebMessageFormat.Xml, ResponseFormat= WebMessageFormat.Xml), OperationContract]
public SampleItem Create(SampleItem instance)
{
return new SampleItem() { Id = 1, StringValue = "saved" };
// TODO: Add the new instance of SampleItem to the collection
//throw new NotImplementedException();
}
I am trying to call this method from my eclipse android project. i am using these lines of codes
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post=new HttpPost("http://10.0.2.2:2768/Service1.svc/save");
ArrayList<NameValuePair> nvp= new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("Id", "1"));
nvp.add(new BasicNameValuePair("StringValue", "yolo"));
post.setEntity(new UrlEncodedFormEntity(nvp));
HttpResponse httpResponse = httpClient.execute(post);
HttpEntity httpEntity = httpResponse.getEntity();
String xml = EntityUtils.toString(httpEntity);
Every time i get this error Method not allowed. in the XML that is returned by the service method.
i have tried invoking it from the browser, but encountered the same error there.
please tell me what i am doing wrong and what i can do instead.
thanks in advance to anyone who can help.
note: other methods which do not use object as parameter are working fine.
EDIT: tried Fiddler2 with success. but stalled again.
i have tried invoking the method SampleItem Create(SampleItem instance) with the url http://localhost:2768/Service1.svc/save and it works. the method returns the object in XML format.
in fiddler i added the request body as
<SampleItem xmlns="http://schemas.datacontract.org/2004/07/WcfRestService1" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Id>1</Id><StringValue>saved</StringValue></SampleItem>
but the problem is that i can not find any way to add this xml string to the HttpPost or HttpRequest as the requestbody eclipse android project.
note: passing the xml string as Header or UrlEncodedFormEntity did not work.
finally i have succeeded to send a json object over to my WCF Service here's my code
URI uri = new URI("http://esimsol.com/droidservice/pigeonlibrary.service1.svc/save");
JSONObject jo1 = new JSONObject();
jo1.put("Id", "4");
jo1.put("StringValue", "yollo");
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestProperty("Content-Type","application/json; charset=utf-8");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("User-Agent", "Pigeon");
conn.setChunkedStreamingMode(0);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(jo1.toString().getBytes());
out.flush();
int code = conn.getResponseCode();
String message = conn.getResponseMessage();
InputStream in = conn.getInputStream();
StringBuffer sb = new StringBuffer();
String reply;
try {
int chr;
while ((chr = in.read()) != -1) {
sb.append((char) chr);
}
reply = sb.toString();
} finally {
in.close();
}
SampleItem SI = new SampleItem();
SI=new Gson().fromJson(reply, SampleItem.class);
Toast.makeText(getApplicationContext(), SI.getStringValue(),Toast.LENGTH_LONG).show();
conn.disconnect();
thanks to StackOverFlow.
i had to combine a number of code snippets to achieve this.
First, you should get the Web Service method working from the browser - I recommend using Fiddler2 - its easier to construct the request body with your object and also to set the request headers when doing a post. It will show you the response so should help with debugging.
As for your code, I'm doing a POST to a WCF service and instead of doing
post.setEntity(new UrlEncodedFormEntity(nvp));
I'm simply doing:
HttpPost request = new HttpPost(url);
// Add headers.
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
(I am using JSONObjects and I have RequestFormat = WebMessageFormat.Json in my WebInvoke parameters.
Also, check your using the correct UriTemplate name in your url as they are case sensitive.
To call that WCF service you must build valid SOAP request and post it. It is better to use some SOAP protocol stack on Android - for example kSoap2.
Here is example of using kSoap2 to call WCF service.
just add KSOAP2 lib in your project.for how we add KSOAP2 in Android project see this post
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.