I develop android application in java. And, this application connects .net soap application. It is ok, it works (i use http post method).
My actual problem is web service returns big and huge (especially contains html --cdata source code) data.
So, when i request (such as, getReports methods) to web service, it returns about 3 - 5 mb stream data, causes outofmemory. Because of this, i couldn't parse it. I know my connection method cannot be true.
How can i implement truely if i make a mistake?
Thanks in advance.
String NAMESPACE = "http://tempuri.org/lorem";
String SURL = "http://www.test.com/lorem/test.asmx";
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
xml += "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://tempuri.org/\">"
+ "<soapenv:Header/><soapenv:Body>"
+ "<web:getReport><web:strLang>strLang</web:strLang></web:getReport>"
+ "</soapenv:Body></soapenv:Envelope>";
URLConnection connection = url.openConnection();
HttpURLConnection httpconn = (HttpURLConnection) connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
bout.write(xml.getBytes());
byte[] b = bout.toByteArray();
httpconn.setRequestProperty("SOAPAction", Namespace+ "/" + "getReport");
httpconn.setRequestProperty("Accept-Encoding","gzip,deflate");
httpconn.setRequestProperty("Host","www.test.com");
httpconn.setRequestMethod("POST");
httpconn.setDoInput(true);
httpconn.setDoOutput(true);
httpconn.connect();
OutputStream out = httpconn.getOutputStream();
out.write(b);
InputStreamReader isr = new InputStreamReader(httpconn.getInputStream());
BufferedReader in = new BufferedReader(isr);
String inputLine = "";
StringBuffer parsingData = new StringBuffer();
while (null != (inputLine = in.readLine())) {
// OutOfMemory Error
parsingData.append(inputLine);
}
/*
* parsingMethods (parsingData);
*/
Ksoap does support headers here is how
Element AuthHeader = new Element();
AuthHeader.setName("Auth");
AuthHeader.setNamespace(namespace);
Element element = new Element();
element.setName("Username");
element.setNamespace(namespace);
element.addChild(Element.TEXT, username);
AuthHeader.addChild(Element.ELEMENT, element);
element = new Element();
element.setName("Password");
element.setNamespace(namespace);
element.addChild(Element.TEXT, password);
AuthHeader.addChild(Element.ELEMENT, element);
headers[0] = AuthHeader;
envelope.headerOut = headers;
Related
I want to send json data via stream to the server, but I struggle to make it work.
I have the following method:
String data = "{\"id\":\"2633\",\"f_name\":\"Test\",\"l_name\":\"Aplikace\",\"city\":\"Nymburk\",\"address\":\"Testovaci 123456789 xyz\",\"psc\":\"288 02\"}";
private String httpPost(String urlString, String data, String session_per) {
StringBuffer sb = new StringBuffer("");
String s1 = "";
try {
URL url = new URL(urlString);
String s2 = "";
HttpURLConnection httpurlconnection = (HttpURLConnection)url.openConnection();
httpurlconnection.setDoInput(true);
httpurlconnection.setDoOutput(true);
httpurlconnection.setUseCaches(false);
httpurlconnection.setRequestMethod("POST");
httpurlconnection.setRequestProperty("Cookie",session_per);
httpurlconnection.setRequestProperty("Authentication-Token", GlobalVar.KLIC);
httpurlconnection.setRequestProperty("Content-type", "application/json");
httpurlconnection.setAllowUserInteraction(false);
OutputStreamWriter outStrWrt = new OutputStreamWriter(httpurlconnection.getOutputStream());
outStrWrt.write(data);
outStrWrt.close();
String s3 = httpurlconnection.getResponseMessage();
//dataoutputstream.flush();
//dataoutputstream.close();
InputStream inputstream = httpurlconnection.getInputStream();
String line = "";
BufferedReader br = new BufferedReader(new InputStreamReader(inputstream));
int i;
while( (line = br.readLine()) != null) {
sb.append(line);
}
s1 = sb.toString();
}
catch(Exception ex)
{
ex.printStackTrace();
s1 = "";
}
return s1;
}
Can anyone tell me why this won't work? The cookies etc. are all correct. Did I miss something important? This is like the 6th method I am trying and I'm starting to get desperate :D
Thank you!
EDIT:
It succesfully connects and the server responds, but it doesn't update user data, as if the json didn't get to the server correctly.
If my Java code is correct there may be a server-side issue.
Try to use flush() method,you don't close this output stream before you read all bytes
outStrWrt.flush();
InputStream inputstream=httpurlconnection.getInputStream();
If you use Java 11, you can try to use HttpClient too.
E.g:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(new URI(urlString)).header("Cookie",session_per).header("Authentication-Token",GlobalVar.KLIC).header("Content-type","application/json").POST(HttpRequest.BodyPublishers.ofString(data)).build();
String datas=client.send(request,BodyHandlers.ofString());
return datas;
I need to fetch content from third party web application UI but after login, site redirects to many pages. I am not understanding how to retrieve data from last opened page.
Presently I am receiving in.readLine() method returns null if I use "OPTIONS" instead of GET.
If I use GET then error 405.
Rest Client shows the connection success through GET method and also redirecting it to desired page.
Please suggest.
I connected to url through URLConnection
HttpsURLConnection con = (HttpsURLConnection) new URL("https://***.com/MRcgi/MRhomepage.pl" + "?" + query).openConnection();
Complete code is as follows-
String charset = "UTF-8"; // Or in Java 7 and later, use the constant:
String USER = "*****";
String PROJECTID = "1";
String MRP = "1eba539717f66151f557b49fd7e8a8d28";//dynamically changes
String OPTION = "none";
String WRITECACHE = "1";
String FIRST_TIME_IN_FP = "1";
String FIRST_TIME_IN_PROJ = "1";
String dispatch_script = "MRlogin.pl";
String query = String
.format("USER=%s&PROJECTID=%s&MRP=%s&OPTION=%s&WRITECACHE=%s&FIRST_TIME_IN_FP=%s&FIRST_TIME_IN_PROJ=%s&dispatch_script=%s&",
URLEncoder.encode(USER, charset),
URLEncoder.encode(PROJECTID, charset),
URLEncoder.encode(MRP, charset),
URLEncoder.encode(OPTION, charset),
URLEncoder.encode(WRITECACHE, charset),
URLEncoder.encode(FIRST_TIME_IN_FP, charset),
URLEncoder.encode(FIRST_TIME_IN_PROJ, charset),
URLEncoder.encode(dispatch_script, charset));
HttpsURLConnection con = (HttpsURLConnection) new URL(
"https://***com/MRcgi/MRhomepage.pl" + "?" + query)
.openConnection();
String userPassword = "domain\\user:password";
String encoding = new String(
org.apache.commons.codec.binary.Base64
.encodeBase64(org.apache.commons.codec.binary.StringUtils
.getBytesUtf8(userPassword)));
System.out.println("----" + encoding);
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "text/plain");
con.setRequestProperty("charset", "UTF-8");
con.setRequestProperty("Authorization", "Basic " + encoding);
USER=user&MRP=15c6ca083c2f75a73e0fbbd2832290f29&PROJECTID=1&USECACHEURL=1&IGNORE_REAL_ACTIVE_TIME=1";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
//wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
System.out.println("-----" + in.readLine());
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
setDoOutput(true) is used for POST and PUT requests. If it is false then it is for using GET requests.
Its not required in my code, so I simply commented setDoOutput(true), and request went as GET
Also below url helped me a lot in understanding it-
What exactly does URLConnection.setDoOutput() affect?
I am tiring to execute some of my project URLs through JAVA APIs. But some of them contain JSON values. Its not accepting the JSON I am providing.
If I hit same URL through browser it executes. I am not getting what is going wrong. Are the " " specified not accepted ?
URL = http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE
The Code is as follows
String requestString = "http://admin.biin.net:8289 /project.do?cmd=AddProject&mode=default&projectJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE"
URL url = new URL(requestString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.connect();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuffer responseString = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
responseString.append(line);
}
Error :
java.io.IOException: Server returned HTTP response code: 505 for URL: http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE
If I remove the JSON the URL executes.
Don't pass json in QueryString. Since you are using HTTP POST. You should send the sensitive data in the HTTP body. Like this
String str = "some string goes here";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.close();
For your current problem. Encode the json value before passing it in url.
Try this:
try {
String s = "http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON="
+ URLEncoder.encode("{\"fieldIds\":[{\"id\":1360,\"value\":\"project SS33\"},{\"id\":1362,\"value\":\"12/03/2015\"},{\"id\":1363,\"value\":\"12/31/2015\"}],\"state\":1}", "UTF-8")
+ "&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE";
System.out.println(s);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Result: http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON=%7B%22fieldIds%22%3A%5B%7B%22id%22%3A1360%2C%22value%22%3A%22project+SS33%22%7D%2C%7B%22id%22%3A1362%2C%22value%22%3A%2212%2F03%2F2015%22%7D%2C%7B%22id%22%3A1363%2C%22value%22%3A%2212%2F31%2F2015%22%7D%5D%2C%22state%22%3A1%7D&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE
I am actually using the community plugin in Neo4j and trying to make POST requests through java to query neo4j server.
I am always getting a java.io.IOException: Server returned HTTP response code: 400
While similar calls to the same url work through javascript, but the business logic suggests making calls through java.
Here is my code snippet:
String baseURL="ip_of_server";
StringBuilder builder = new StringBuilder();
try {
URL url = new URL(baseURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
OutputStream os=connection.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(os,Charset.forName("UTF-8"));
System.out.println(url);
Map<String, Object> params = new HashMap<String, Object>();
params.put("query", "start x = node(3) return x");
HashMap<String,String> test3= new HashMap<String,String>();
params.put("params", test3);
ObjectMapper temp = new ObjectMapper();
String testString= temp.writeValueAsString(params);
writer.write(testString);
writer.close();
os.close();
String line = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
System.out.println("Response from server for request : " + url.toString() + " is " );
System.out.println(builder.toString());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Any suggestions?
What it requires is a parser, since '=' etc are converted by the encoding into other characters, hence neo4j throws an error
I want to authenticate a user using the zm_auth_token that I dispose :
For the moment, I'm doing this :
LmcAuthRequest auth = new LmcAuthRequest();
auth.setUsername(userName);
auth.setPassword(password);
LmcAuthResponse authResp = (LmcAuthResponse) auth.invoke(serverURL);
LmcSession session = authResp.getSession();
But I want to use the zm_auth_token that I have. How to do this ???
Thnx
The zimbra Lmc methods are deprecated now ...
If you want to use SOAP they prefer doing it using ZMailBox (It doesn't work for me), I used this method :
// Create the connection where we're going to send the file.
URL url = new URL(SOAPUrl);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
String postContent = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\">"+
"<soap:Header>" +
"<context xmlns=\"urn:zimbra\">" +
"<format type=\"js\"/>" +
"<authToken>" + authToken + "</authToken>" +
"</context>" +
"</soap:Header>" +
"<soap:Body>" +
"<GetFolderRequest xmlns=\"urn:zimbraMail\" />" +
"</soap:Body>" +
"</soap:Envelope>";
// insert your SOAP XML!!!
byte[] b = postContent.getBytes();
// Set the appropriate HTTP parameters.
httpConn.setRequestProperty( "Content-Length", String.valueOf( b.length ) );
httpConn.setRequestProperty("Content-Type","application/soap+xml; charset=utf-8");
httpConn.setRequestMethod( "POST" );
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
// Everything's set up; send the XML that was read in to b.
OutputStream out = httpConn.getOutputStream();
out.write( b );
out.close();
// Read the response and write it to standard out.
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
// read & do something with input stream...
String s = null;
String response = "";
while((s=in.readLine()) != null){
response += s;
}
in.close();
SOAPConnectionFactory soapfactory=SOAPConnectionFactory.newInstance();
SOAPConnection soapconnection=soapfactory.createConnection();
MessageFactory messagefactory=MessageFactory.newInstance();
SOAPMessage messege=messagefactory.createMessage();
SOAPEnvelope envelop=messege.getSOAPPart().getEnvelope();
SOAPHeader header=messege.getSOAPHeader();
SOAPBody body=messege.getSOAPBody();
Name header_context=envelop.createName("context", null,"urn:zimbra");
Name auth_request=envelop.createName("AuthRequest",null,"urn:zimbraAccount");
Name account=envelop.createName("account");
Name password=envelop.createName("password");
header.addHeaderElement(header_context);
SOAPBodyElement auth_body=body.addBodyElement(auth_request);
auth_body.addChildElement(account).addAttribute(envelop.createName("by"),"name").addTextNode("abc");//(abc==your username)
auth_body.addChildElement(password).addTextNode("1234");//(1234=your password)
URL url=new URL("http://192.168.1.67/service/soap/AuthRequest");
SOAPMessage response=soapconnection.call(messege, url);
You can use Zimbra libraries for calling SOAP API. Please check this answer.