Http soap request doesn't return anything - java

I'm trying to do a soap request via a http post. According to this https://t4t.services.telenet.be/TelemeterService?wsdl that shows https://t4t.services.telenet.be/TelemeterService?xsd=1
I need to post a Id and password.
This is my request:
public static void main(String[] args) {
try {
callWebService("retrieveUsage");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void callWebService(String soapaction) throws IOException {
String body = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:tns=\"http://www.telenet.be/TelemeterService/\" xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ><SOAP-ENV:Body><mns1:RetrieveUsageRequest xmlns:mns1=\"http://www.telenet.be/TelemeterService/\"><UserId>test</UserId><Password>test</Password></mns1:RetrieveUsageRequest></SOAP-ENV:Body></SOAP-ENV:Envelope>";
HttpPost httppost = new HttpPost("https://t4t.services.telenet.be/TelemeterService");
// Request parameters and other properties.
StringEntity stringentity = new StringEntity(body, "UTF-8");
stringentity.setChunked(true);
httppost.setEntity(stringentity);
httppost.addHeader("Accept", "text/xml");
httppost.addHeader("SOAPAction", soapaction);
//Execute and get the response.
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String strresponse = null;
if (entity != null) {
strresponse = EntityUtils.toString(entity);
}
System.out.println(strresponse);
System.out.println("Done");
}
I'm using apache http.
The strresponse is empty.
Is there something wrong with my code?

Related

Android do PATCH/PUT to server

I'm having this issue and I need to put or patch data to the server. I know how to do a standard post, but how can I do this PATCH or PUT to the server?
The URL to the server is PATCH to www.example.com/api/documents and parameter is doc_id(integer).
This is what I currently have
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("content-type", "application/json");
httpPost.setHeader("accept-charset", "utf8");
try {
HttpResponse response = httpClient.execute(httpPost);
responseString = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
Log.e("Request exception:", "excpetion", e);
}
return responseString;
But this code I think is wrong as hell :)
This is the most common way---
Creating jsonObj and putting json values:
JSONObject jsonObj = new JSONObject();
jsonObj .put("doc_id", <put your value> + "");
String response = callPutService(source, password, callingAPI, jsonObj);
This is the callPutService that is called:
public String callPutService(String userName, String password,
String type, JSONObject jsonObject) {
String line = null, jsonString = "";
HttpResponse response = null;
InputStream inputStream = null;
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.
setConnectionTimeout
(client.getParams(), 20000); // Timeout Limit
HttpPut put = new HttpPut(WEBSERVICE + type);
StringEntity se = new StringEntity(jsonObject.toString());
se.setContentType("application/json;charset=UTF-8");
put.setHeader("Authorization",
"basic " + Base64.
encodeToString((userName + ":" + password).getBytes(),
Base64.URL_SAFE | Base64.NO_WRAP));
put.setEntity(se);
response = client.execute(put);
int responseCode = response.getStatusLine().getStatusCode();
if(responseCode == 200){
//do whatever
}
} catch (Exception e) {
e.printStackTrace();
}
return jsonString;
}

Sending parameters via POST to php file and reading php file's echo

I am sending NameValuePair parameters to a php file on my server and this php file echoes one of three string values.
I need to write code in Java to send these parameters to the PHP file via POST and also save the php file's echo response to a String.
This is what I have so far:
public String getStringFromUrl(String url, List<NameValuePair> params) throws IOException {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
HttpPost httpPost = new HttpPost(url);
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
String response2 = (String) response;
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return response;
}
I know I have the right lines of code for sending the POST parameters but how do I read the value the php file echoes corresponding to the given POST parameters?
You can read the post response this way:
HttpResponse response = client.execute(post);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
See the full example here:
http://www.mkyong.com/java/apache-httpclient-examples/

Getting "Invalid JSON primitive" error while trying to get data from WebService

I'm working on an android app and I want to get some data from a WebService. I'm using this code to get JSON data from the WebService.
TextView textv=(TextView) findViewById(R.id.textv);
try {
HttpClient client = new DefaultHttpClient();
String URL = "http://server/WebService.asmx/Get_ActiveFair";
HttpPost post = new HttpPost(URL);
post.setHeader("Content-Type", "application/json; charset=utf-8");
HttpResponse responsePost = client.execute(post);
HttpEntity resEntityPost = responsePost.getEntity();
if (resEntityPost != null)
{
String response=EntityUtils.toString(resEntityPost);
Log.e("XXX",response);
textv.setText(response);
}
} catch (Exception e) {
e.printStackTrace();
textv.setText(e.toString());
Log.e("error!!",e.toString());
}
It works correctly an I get the data like this:
{
"d": "{\"Id\":2,\"Name\":\"Fair Name \",\"IsActive\":true,\"Date_Start\":\"\\/Date(1383343200000)\\/\",\"Date_End\":\"\\/Date(1384034400000)\\/\",\"Url_Map\":null,\"Details\":\"Fair Details \",\"Address\":\"FairAdress \",\"VisitingInfo\":\"Fair Visiting Info\",\"Contact\":null,\"Transportation\":\" Fair Transportation Info \"}"
}
But when I want to use another method in the webservice which needs to get FairId I get the result:
{
"Message": "Invalid JSON primitive: FairId.",
"StackTrace": " at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)",
"ExceptionType": "System.ArgumentException"
}
And here is my code to run the Get_EventList method:
TextView textv=(TextView) findViewById(R.id.textv);
try {
HttpClient client = new DefaultHttpClient();
String URL = "http://server/WebService.asmx/Get_EventList";
HttpPost post = new HttpPost(URL);
List<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("FairId", "2"));
post.setEntity(new UrlEncodedFormEntity(postParameters));
post.setHeader("Content-Type", "application/json; charset=utf-8");
HttpResponse responsePost = client.execute(post);
HttpEntity resEntityPost = responsePost.getEntity();
if (resEntityPost != null)
{
String response=EntityUtils.toString(resEntityPost);
Log.e("XXX",response);
textv.setText(response);
}
} catch (Exception e) {
e.printStackTrace();
textv.setText(e.toString());
Log.e("hata!!",e.toString());
}
What can be the problem? How can I solve it?
I solve the problem by sending FairId to WebService with JSONObject. Here is my new code:
TextView textv=(TextView) findViewById(R.id.textv);
try {
HttpClient client = new DefaultHttpClient();
String URL = "http://server/WebService.asmx/Get_EventList";
HttpPost post = new HttpPost(URL);
JSONObject json = new JSONObject();
json.put("FairId", "2");
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse responsePost = client.execute(post);
HttpEntity resEntityPost = responsePost.getEntity();
if (resEntityPost != null)
{
String response=EntityUtils.toString(resEntityPost);
Log.e("XXX",response);
textv.setText(response);
}
} catch (Exception e) {
e.printStackTrace();
textv.setText(e.toString());
Log.e("hata!!",e.toString());
}

grails receive file via MultipartEntity

I use this httpclient to post a image to my grails as follows. How do I receive the file in grails?
public static String webPost(String method, File data, Context c) throws Exception {
String json = "";
if (isOnline(c) == true) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
HttpPost httppost ;
try {
httppost = new HttpPost(method);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("image", new FileBody(data));
httppost.setEntity(entity);
response = httpclient.execute(httppost);
if (response != null) {
HttpEntity r_entity = response.getEntity();
json = EntityUtils.toString(r_entity);
Log.i("ja", json);
}
} catch (Exception e) {
throw new RuntimeException(e.getLocalizedMessage());
} finally {
httpclient = null;
response = null;
httpclient = null;
}
} else {
throw new RuntimeException("No internet connection");
}
return json;
}
My grails:
def image = request.getFile('image')
image.transferTo(new File('c:/p.png') )
Error:
groovy.lang.MissingMethodException: No signature of method: org.apache.catalina.core.ApplicationHttpRequest.getFile() is applicable for argument types: (java.lang.String) values: [image]
Possible solutions: getXML(), getAt(java.lang.String), getAt(java.lang.String), getLocale(), getInfo(), recycle()
at mclient.TestController$_closure1.doCall(TestController.groovy:10)
at mclient.TestController$_closure1.doCall(TestController.groovy)
at java.lang.Thread.run(Thread.java:662)

Send key-value parametres and json message body throught http post request

I need to send http POST request from mobile android application to the server side applcation.
This request need to contain json message in body and some key-value parametres.
I am try to write this method:
public static String makePostRequest(String url, String body, BasicHttpParams params) throws ClientProtocolException, IOException {
Logger.i(HttpClientAndroid.class, "Make post request");
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(body);
httpPost.setParams(params);
httpPost.setEntity(entity);
HttpResponse response = getHttpClient().execute(httpPost);
return handleResponse(response);
}
Here i set parametres to request throught method setParams and set json body throught setEntity.
But it isn't work.
Can anybody help to me?
You can use a NameValuePair to do this..........
Below is the code from my project where I used NameValuePair to sent the xml data and receive the xml response, this will provide u some idea about how to use it with JSON.
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now",sb+"");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sb.toString());
return sb.toString();
}

Categories