There is a relevant question, but I could not get the answer clearly.
I would like to POST a short xml code
<aaaLogin inName="admin" inPassword="admin123"/>
to a specific URL address over HTTP. The Web service will send me back a XML code. The important part is that I will parse the received XML, and I want to store that as a file.
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.192.131/"); //URL address
StringEntity se = new StringEntity("<aaaLogin inName=\"admin\" inPassword=\"admin123\"/>",HTTP.UTF_8); //XML as a string
se.setContentType("text/xml"); //declare it as XML
httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
httppost.setEntity(se);
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient .execute(httppost);
tvData.setText(httpResponse.getStatusLine().toString()); //text view is expected to print the response
there is something wrong with receiving the response. Besides, I did not write anything to save the received XML as a file. Can someone write a code snippet?
Ok, I have figured out soon after I posted this question.
This code here works fine:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.192.131/");
try {
StringEntity se = new StringEntity( "<aaaLogin inName=\"admin\" inPassword=\"admin123\"/>", HTTP.UTF_8);
se.setContentType("text/xml");
httppost.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity resEntity = httpresponse.getEntity();
tvData.setText(EntityUtils.toString(resEntity));
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can get the content of the response using:
String responseXml = EntityUtils.toString(httpResponse.getEntity());
You can then write this to a file using something like this.
there is something wrong with receiving the response
Since you havn't said what is wrong with receiving the response it's somewhat difficult to help you with this point.
Why not use Spring RestTemplate in Spring for Android?
Related
I know that this is a duplicate Question. But i didn't get the proper answer. My question is that. I have some data and i want to convert that data into xml and i want to send this xml with HttpPost request. When This Post request is executed then it give me data in xml format. then i want to parse the xml data. Please tell me the best way to do it. I have read Some tutorial but I haven't get proper answer. is there no other way to convert object value into xml accounting to the class field Like marshaling and unmarshaling in java please tell me the answer. Thanks in advance. I have read some example here are some links. click here and here
Simple example for XML parser using HTTP POST,
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.192.131/");
try {
StringEntity se = new StringEntity( "<aaaLogin inName=\"admin\" inPassword=\"admin123\"/>", HTTP.UTF_8);
se.setContentType("text/xml");
httppost.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity resEntity = httpresponse.getEntity();
tvData.setText(EntityUtils.toString(resEntity));
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am trying to post two json encoded values to my webservice using the below code. but i am not getting any response (Just Blank Output and No errors on LogCat). However, I have tried posting the same parameters from PHP to my webservice using cURL which works great.
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
try {
json.put("name","email");
json.put("email", "email");
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept-Encoding", "application/json");
post.setHeader("Accept-Language", "en-US");
List<NameValuePair> ad = new ArrayList<NameValuePair>(2);
ad.add(new BasicNameValuePair("json", json.toString()));
post.setEntity(new UrlEncodedFormEntity(ad));
Log.i("main", "TestPOST - nVP = "+ad.toString());
response = client.execute(post);
if(response!=null) {
HttpEntity entity = response.getEntity();
output = EntityUtils.toString(entity,HTTP.UTF_8); //Get the data in the entity
}
} catch(Exception e) {
}
Try Getting your response by this
if (response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
json = EntityUtils.toString(entity);
}
You're catching Exception (the super class) without logging. If an exception of any kind occurs in your try block the code will jump to the catch without any log.
Change this:
catch(Exception e){
}
with
catch (Exception e)
Log.e("myappname", "exception", e);
}
If there is no response, you should definitely check your catch exception e, since you didn't write anything in the clause, there might be something happening but you didn't notice.
I am trying to POST json to a URL from an android app. I went through every relevant answer I found here, but whatever I do, I am getting status code 406. I learned that means server isn't accepting the format of what I am sending, but I can't find what is wrong with what I am doing.
Here is the relevant code:
#Override
protected HttpResponse doInBackground(Void... params) {
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient httpclient = new DefaultHttpClient(httpParams);
HttpPost httpPost = new HttpPost(URL);
HttpResponse httpResponse = null;
httpPost.setHeader("Content-Type", "application/json");
Log.w("json: ", formJSON().toString());
try {
StringEntity se = new StringEntity(formJSON().toString());
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
httpPost.setEntity(se);
httpResponse = httpclient.execute(httpPost);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return httpResponse;
}
I checked the JSON formed by my formJSON() method through JSONLint and it was valid. BTW, the json I am expected to send is { String, String, String, String and String[] }
EDIT:
I found the answer myself. It seems during testing, I was sending some strings empty, so the POST was 406, "not in acceptable format". Once I tried filling everything manually, I got 200 back.
Here is my doInBackground() method in which I call my makeHttpRequest() method which is in other class.
protected String doInBackground(Integer... args) {
// Building Parameters
String parameter1 = "tenant";
String parameter2 = "price";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("person",parameter1));
params.add(new BasicNameValuePair("price",parameter2));
JSONObject json = jParser.makeHttpRequest(requiredurl, "POST", params);
Log.d("Details", json.toString());
int success = json.getInt("connected");
if (success == 1) {
//blah blah
}
}
makeHttpRequest() method:
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
................
....................... // Here the result is extracted and made it to json object
.............................
// return JSON
return jObj; // returning the json object to the method that calls.
}
So, by the above code, the actual call to the server is made by this line -> HttpResponse httpResponse = httpClient.execute(httpPost);
When my server is up everything works fine, but when it is down the progress bar continuously loads. I want to handle this situation. Have done lot of search, but could find only this post. This looks good for my situation because even my thought is to wait for the 10 seconds to get the response and if it exceeds that time out, I need to handle it to show the message in the catch block. But I am unable to implement it according to my code. Can some one please help me on this? I would be very thankful.
Your exceptions are not getting hit because the HttpClient is not throwing an exception. Perhaps you are getting an error in your HttpResponse code, such as a 500. In your try block, add this line:
response.getStatusLine().getStatusCode()
Then read the status code. If your web server is up you should get a 200 OK, but if it's down, you'll probably get a 500 or something else. You can then handle the code here where your spinning progress bar needs to be hidden, and an error message can be displayed.
Add Following Code before executing the url.
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
HttpConnectionParams.setSoTimeout(httpParameters, 30000);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
write the above code in try block and Catch ConnectTimeOutException and SocketConnectionTimeOutException. Where you can show some custom dialog.
You can also judge it by checking the status line of HttpClient Response.
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.