I'm new in webservice.
I've to pass xml to aspx web service called plog.asmx
here is my code
String xmldata = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<SOAP:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" >" +
"<![CD[<soap:Body>" +
"<SubmitJob xmlns=\"http://www.xdel.biz/XWS/\"> " +
"<APIKey>"+ API_KEY +"</APIKey>" +
"<Job>" +
"<Customer_Name>"+ Customer_Name +"</Customer_Name>" +
"<Address1>"+ Address1 +"</Address1>" +
"<Address2>"+ Address2 +"</Address2>" +
"<Postal_Code>"+ Postal_Code +"</Postal_Code>" +
"<Phone_Number>"+ Phone_Number +"</Phone_Number>" +
"<Mobile_Number>"+ Mobile_Number +"</Mobile_Number>" +
"<Order_Reference>"+ Order_Reference +"</Order_Reference>" +
"<Delivery_Instructions>"+ Delivery_Instructions +"</Delivery_Instructions>" +
"</Job>]]>" +
"</SubmitJob>" +
"</soap:Body>]]>" +
"</SOAP:Envelope>";
System.out.println(xmldata);
try{
//Create socket
String hostname = "www.xdel.biz";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket sock = new Socket(addr, port);
System.out.println(sock.toString());
//Send header
String path = "/xws/plog.asmx";
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"UTF-8"));
// You can use "UTF8" for compatibility with the Microsoft virtual machine.
wr.write("POST " + path + " HTTP/1.1\r\n");
wr.write("Host: www.xdel.biz\r\n");
wr.write("Content-Type: text/xml; charset=utf-8\r\n");
wr.write("Content-Length: " + xmldata.length() + "\r\n");
wr.write("SOAPAction: \"http://www.xdel.biz/XWS/SubmitJob\" \r\n");
wr.write("\r\n");
//Send data
wr.write(xmldata);
wr.flush();
System.out.println("1");
// Response
BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String line;
while((line = rd.readLine()) != null){
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
when I run the code, I got error like this
HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 13 Dec 2012 09:37:12 GMT
Content-Length: 0
I googled the error and tried to fix but no solution come out..
A good ideia would be to use an API that implements SOAP webservice and is already tested.
I used this
JAX-WS
400 Bad Request sometimes happens when you mismatch the protocol(SOAP or HTTP)
It could be <![CD[<soap:Body></soap:Body>]]> try to use without ![CD[ ]] block
I already had "Bad Request" consuming a webservice. The thing is, after almost a day looking for an answer, we found out that was the size of the XML consumed, the size of the SOAP Message consumed. The problem is, the application that provides the Webservice to be consumed, must be set up to receive a large XML Data, we had to config our application server to expand to encrease the size of our buffer used to receive the SOAP Message from the client.
That was our expirence. I hope could helps a little.
I had same issue with HttpURLConnection. Adding the below two properties resolved my 400 Bad Request issue:
httpConn.setRequestProperty("Content-Type","text/xml; charset=utf-8");
httpConn.setRequestProperty("soapAction", soapAction);
Note: this error usually appears when you try to read response.
Related
I am trying to do a simple servlet connection socket,
I am able to see this webpage and able to get to my servlet(on another eclipse instance) breakpoint when using a web browser.
but when i try to perform the following function:
public void Connect() {
try {
String params = URLEncoder.encode("ID", "UTF-8")
+ "=" + URLEncoder.encode("test", "UTF-8");
params += "&" + URLEncoder.encode("GOAL", "UTF-8")
+ "=" + URLEncoder.encode("Security", "UTF-8");
URL url = new URL(_address);
String host = url.getHost();
int port = url.getPort();
String path = url.getPath();
Socket socket = new Socket(host, port);
// Send headers
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
wr.write("GET " + path + " HTTP/1.0\r\n");
wr.write("Content-Length: " + params.length() + "\r\n");
wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
wr.write("\r\n");
// Send parameters
wr.write(params);
wr.flush();
// Get response
BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
String answer = "";
while ((line = rd.readLine()) != null) {
answer += line;
}
wr.close();
rd.close();
if (answer.indexOf(resourceStrings.ACCESS_GRANTED) != -1)
{
_result = true;
}
}
catch (Exception e) {
_result = false;
}
}
I just recieve the following answer:
HTTP/1.1 302 Found
Server: Apache-Coyote/1.1
Location: http://localhost:8180/Admin/
Date: Mon, 18 Apr 2016 15:00:28 GMT
Connection: close
without getting to my servlet code's breakpoint or retrieve any data from my "service" function in the servlet.
I am using Tomcat 7 if it makes any difference, do you have any idea what is causing this issue?
The parameters of a GET request are sent by appending them to the URL, not in the body of the request.
I am new to Socket Programming , I have written a program to send get request via HttpURLConnection (it is working fine),
Output I got :
Some XML Data (ie Valid Data)
Now i want to implement same in Socket Programming.
String ul = "http://www.xxxxxxxx.com/cgi-bin/yyyy.cgi?name=abcd&age=25&phone=01454575";
URL url = new URL(ul);
Socket cliSocket = new Socket();
cliSocket.connect(new InetSocketAddress(url.getHost(), 80), 6000);
bw = new BufferedWriter(new OutputStreamWriter(cliSocket.getOutputStream()));
bw.write("GET " + url.getPath() + " HTTP/1.0\r\n");
bw.write("Host: " + url.getHost() + "\r\n");
bw.write("Pragma: cache\r\n");
bw.write("Cache-Control: private, must-revalidate\r\n");
bw.write("Content-Type: application/x-www-form-urlencoded\r\n");
bw.write("\r\n");
bw.flush();
rd = new BufferedReader(new InputStreamReader(cliSocket.getInputStream()));
serverData = new StringBuffer("");
lineSep = System.getProperty("line.separator");
while ((line = rd.readLine()) != null) {
serverData.append(line);
serverData.append(lineSep);
}
data = serverData.toString();
Output I am getting is
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 28 May 2014 09:55:25 GMT
Content-Type: text/html
Connection: close
{Error: 1}
I'm currently working on an upload test using java sockets. I've found an example using httpurlconnection but for the purposes of my assignment I must do it manually with sockets. Also, the server I will be using, does not accept HTTP PUT requests, and only accepts POST requests. Therefore, in there I have a line which looks like this:
conn = new Socket(server, 80);
outToServer = new DataOutputStream(conn.getOutputStream());
inFromServer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
outToServer.writeBytes("POST...etc...");
I am not quite sure how to format the POST request. Here is how I had formated the PUT request which failed because the server I am using does not accept PUT requests:
outToServer.writeBytes("PUT /url/test1.txt HTTP/1.1\r\n"
+ "Host: url.edu\r\n"
+ "Content-Type: plain/text\r\n"
+ "Connection: close\r\n\r\n");
Any help is greatly appreciated.
Try this
Socket conn = new Socket(server, 80);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF8"));
writer.write("POST " + "http://www.example.com" + " HTTP/1.0\r\n");
writer.write("Content-Length: " + data.length() + "\r\n");
wr.write("Content-Type: plain/text\r\n");
writer.write("\r\n");
writer.write(data);
writer.flush();
I'am trying to implement a simple HTTP/1.1 client application against a remote HTTP server. If I have a 301 Moved Permanently response from server, I will try to download the file from it's new location given in server's response. I am able to send first GET message to server and retrieve the new URL where the file I asked was moved.
The problem is that when I send second GET request from my client with new location of the file, server returns null. Not sure if anything goes wrong with writing the client message or reading the server response. Here is my code, any help is appreciated.
else if(serverMessage.equals("HTTP/1.1 301 Moved Permanently"))
{
System.out.println(" A new permanent URL is assigned to the file " + fileName);
serverMessage="";
lineCount=0;
while((serverMessage = reader.readLine()) != null)
{
lineCount++;
System.out.println("reply: " + serverMessage);
if(serverMessage.indexOf("Location") >= 0 )
{
for(int x=serverMessage.indexOf("Location")+10; x<serverMessage.length(); x++)
{
newURL= newURL + serverMessage.charAt(x);
}
}
}
System.out.println("newURL : " + newURL);
host = findHost(newURL);
path = findPath(newURL);
fileName=findFileName(newURL);
clientMessage = "GET ";
clientMessage = clientMessage + path;
clientMessage = clientMessage + " HTTP/1.1\r\nHost: ";
clientMessage = clientMessage + host;
clientMessage = clientMessage + "\r\n\r\n";
System.out.println("client message: \"" + clientMessage +"\"");
writer.newLine();
writer.write(clientMessage);
writer.flush();
serverMessage = reader.readLine();
System.out.println("reply2: " + serverMessage); //returns null!!!
while((serverMessage=reader.readLine())!=null)
{
System.out.println("reply2: " + serverMessage);
}
}
EDIT: Variables of client message are the followings (they all work correctly, tested for existing file - successfully downloaded!)
newURL : http://wlab.cs.bilkent.edu.tr/~cs421/pa1/302-redirect-success.txt
host2: wlab.cs.bilkent.edu.tr
path2: /~cs421/pa1/302-redirect-success.txt
fileName2: 302-redirect-success.txt
Are you using a persistent URLConnection / HttpURLConnection?
You may be receiving null if the connection has been closed by the server.
If you are using persistent connections, the server might have not had the time to respond.
This might describe the problem a little better. Check out the timeout given in doHttpUrlConnectionAction(String desiredUrl). You might find the answer there.
If this is your problem, you can try to do multiple reads at 0.1 second intervals for say ... 1-5 seconds. This is to make sure you get the response fast and don't have to wait the full timeout to make sure that the server has responded.
I'm trying to build a small Java app for connecting to an application called CampFire and am running into trouble trying to upload files to the system. The Java code I'm using to upload a file is as follows:
public static String postFile(String requestUri, File f)
{
debug("Running postFile.");
logIn();
debug("Sending File: " + f.getAbsolutePath() + " to " + campFireURL + requestUri);
URL url;
URLConnection conn;
String linebreak = "\r\n";
String boundary = "**********xxx**********";
String twoHyphens = "--";
String result = "";
String request = twoHyphens + boundary + linebreak +
"Content-Disposition: form-data; name=\"upload\"; filename=\"" + f.getName() + "\"" + linebreak +
linebreak +
"";
debug("Request: " + request);
try
{
FileInputStream in = new FileInputStream(f);
auth.resetTries();
Authenticator.setDefault(auth);
// Send data
url = new URL(campFireURL + requestUri);
conn = url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(request);
int i;
while((i = in.read()) != -1)
{
wr.write(i);
}
wr.writeBytes(linebreak + twoHyphens + boundary + twoHyphens + linebreak);
wr.flush();
wr.close();
in.close();
result = readFromConnection(conn);
}
catch (Exception e)
{
debug(e);
JOptionPane.showMessageDialog(null, "Error running postData: " + e.getMessage(), "HTTP POST Error", JOptionPane.ERROR_MESSAGE);
die();
}
return(result);
}
When I run this with a real file though, I get the following errors...
Running postFile.
Sending File: /home/myuser/Desktop/blah.png to https://blah.campfirenow.com/room/blah/uploads.xml
Request: --**********xxx**********
Content-Disposition: form-data; name="upload"; filename="blah.png"
Server returned HTTP response code: 422 for URL: blah blah
java.io.IOException: Server returned HTTP response code: 422 for URL: blah blah
Any idea's what I'm doing wrong here? I'm fairly new at Java and am wondering if maybe I missed something obvious?
HTTP error 422 means "Unprocessable Entity". After a quick glance I can spot one mistake: a PNG file is a binary file. You've to add Content-Transfer-Encoding: binary to the header of the part.
If it still doesn't work, then you may find the example in the Uploading files section at the bottom of this answer useful.