I need to send a xml file to the following link\
http://14.140.66.142:80/MSMQ/private$/votes
This is my code.
URL url = new URL("http://14.140.66.142:80/MSMQ/private$/votes");
URLConnection con = url.openConnection();
String document = "C:\\Documents and Settings\\Nagra\\My Documents\\Responseserver\\workingVoting\\VoteSubmitter\\Body.xml";
FileReader fr = new FileReader(document);
// specify that we will send output and accept input
con.setDoInput(true);
con.setDoOutput(true);
char[] buffer = new char[1024*10];
int b_read = 0;
if ((b_read = fr.read(buffer)) != -1)
{
con.setRequestHeader ( "Content-Type", "text/xml" );
con.setRequestProperty("SOAPAction","MSMQMessage");
con.setRequestProperty("Proxy-Accept","NonInteractiveClient" );
con.setRequestProperty("CONNECTION", "close");
con.setRequestProperty("CACHE-CONTROL", "no-cache");
con.setRequestProperty("USER-AGENT", "OpenTV-iAdsResponder_1_0");
OutputStreamWriter writer = new OutputStreamWriter( con.getOutputStream() );
writer.write(buffer, 0, b_read);
PrintWriter pw = new PrintWriter(con.getOutputStream());
pw.write(buffer, 0, b_read);
pw.close();
System.out.println("written");
}
catch( Throwable t )
{
t.printStackTrace( System.out );
}
}
}
I don't Know whether it is right code.If i run this code I am not able to receive the xml file on the server side.Can anyone help me where i gone wrong in my code.
Below is a sample POST operation:
URL url = new URL("http://14.140.66.142:80/MSMQ/private$/votes");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/xml");
OutputStream os = connection.getOutputStream();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
FileReader fileReader = new FileReader("C:\\Documents and Settings\\Nagra\\My Documents\\Responseserver\\workingVoting\\VoteSubmitter\\Body.xml");
StreamSource source = new StreamSource(fileReader);
StreamResult result = new StreamResult(os);
transformer.transform(source, result);
os.flush();
connection.getResponseCode();
connection.disconnect();
There are a couple of issues with the code you have posted.
First, you are reading only 1024*10 characters and you are not sending the whole file if the file has more characters. Second, you are writing the content more than once. Change the code something similar to this.
URL url = new URL("http://14.140.66.142:80/MSMQ/private$/votes");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
String document = "C:\\Documents and Settings\\Nagra\\My Documents\\Responseserver\\workingVoting\\VoteSubmitter\\Body.xml";
FileReader fr = new FileReader(document);
// specify that we will send output and accept input
con.setDoInput(true);
con.setDoOutput(true);
char[] buffer = new char[1024*10];
int b_read = 0;
con.setRequestProperty ( "Content-Type", "text/xml" );
con.setRequestProperty("SOAPAction","MSMQMessage");
con.setRequestProperty("Proxy-Accept","NonInteractiveClient" );
con.setRequestProperty("CONNECTION", "close");
con.setRequestProperty("CACHE-CONTROL", "no-cache");
con.setRequestProperty("USER-AGENT", "OpenTV-iAdsResponder_1_0");
OutputStreamWriter writer = new OutputStreamWriter( con.getOutputStream() );
while ((b_read = fr.read(buffer)) != -1) {
writer.write(buffer, 0, b_read);
}
writer.flush();
writer.close();
fr.close();
int i = con.getResponseCode();
con.disconnect();
System.out.println(String.format("written with response code: %d",i));
Related
I have this current code. The file is in memory on the InputStream in or in test.pdf. I would prefer to only keep in-memory.
FileOutputStream fos = new FileOutputStream(new File("test.pdf"));
// Read file
InputStream in = url.openStream();
while((bufferLength = in.read(buffer)) != -1) {
fos.write(buffer, 0, bufferLength);
}
fos.flush();
// Close connections
fos.close();
in.close();
System.out.println("GOT DOCUMENT");
String submitURl = "https://someURL/submit";
// Send data
HttpURLConnection conn = (HttpURLConnection) new URL(submitURl).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type","multipart/form-data");
conn.setRequestProperty("User-Agent", "Test Agent");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
How do I post this file to the /submit URL. What am I missing here?
String httpsURL = "https://m.facebook.com/login/identify/?ctx=recover&c=https%3A%2F%2Fm.facebook.com%2Flogin%2F&lwv=100&_rdr";
String query = "email="+URLEncoder.encode("myemailaddress#gmail.com","UTF-8");
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
DataInputStream input = new DataInputStream( con.getInputStream() );
for( int c = input.read(); c != -1; c = input.read() )
System.out.print( (char)c );
input.close();
System.out.println("Resp Code:"+con .getResponseCode());
System.out.println("Resp Message:"+ con .getResponseMessage());
![enter image description here](https://i.stack.imgur.com/gVUc3.png)![enter image description here](https://i.stack.imgur.com/3RihL.png)
I made the below 2 changes to your code to make it work:
1) Removed the _rdr parameter from the end of the URL. Looks like when you add that, it always redirects you to the initial page. So:
String httpsURL = "https://m.facebook.com/login/identify/?ctx=recover&c=https%3A%2F%2Fm.facebook.com%2Flogin%2F&lwv=100";
2) When following redirects, HttpsURLConnection doesn't set cookies it got from the original response, unless you do this (More info):
CookieHandler.setDefault(new CookieManager());
Putting these two together, we have the final working code below. Here is a working demo. I added BufferedReader to read the response for slightly better looking console output, this is not necessary for it to work.
String httpsURL = "https://m.facebook.com/login/identify/?ctx=recover&c=https%3A%2F%2Fm.facebook.com%2Flogin%2F&lwv=100";
String query = "email=" + URLEncoder.encode("myemailaddress#gmail.com", "UTF-8");
CookieHandler.setDefault(new CookieManager());
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
BufferedReader input = new BufferedReader(new InputStreamReader(con.getInputStream()));
for (int c = input.read(); c != -1; c = input.read())
System.out.print((char) c);
input.close();
System.out.println("Resp Code:" + con.getResponseCode());
System.out.println("Resp Message:" + con.getResponseMessage());
When i run this code it gives me error xml stating---Problem processing POST request: unsupported Content-Type text/xml. I want to send an xml using httpClient to a URL which is a web service url
public class HTTPClientDemo {
public static void main(String[] args) {
try
{
String inputXML = "<Style>0206.ard</Style><BoardCode>I-175B</BoardCode><BoardDesc>I-175 B Kraft</BoardDesc><GrainDirection>Vertical</GrainDirection><Unit>mm</Unit><PrintSide>Inside</PrintSide><Length>100</Length><Width>70</Width><Depth>45</Depth>";
URL url = new URL( "http://egwinae002:4415/ws/wstest003" );
// URL url = new URL( "https://dzone.com/articles/using-java-post-block-xml-web" );
URLConnection con = url.openConnection();
// con.connect();
// specify that we will send output and accept input
con.setDoInput(true);
con.setDoOutput(true);
con.setConnectTimeout( 20000 ); // long timeout, but not infinite
con.setReadTimeout( 20000 );
con.setUseCaches (false);
con.setDefaultUseCaches (false);
// tell the web server what we are sending
con.setRequestProperty ( "Content-Type", "text/xml" );
OutputStreamWriter writer = new OutputStreamWriter( con.getOutputStream() );
writer.write( inputXML );
writer.flush();
writer.close();
// reading the response
InputStreamReader reader = new InputStreamReader( con.getInputStream() );
StringBuilder buf = new StringBuilder();
char[] cbuf = new char[ 2048 ];
int num;
while ( -1 != (num=reader.read( cbuf )))
{
buf.append( cbuf, 0, num );
}
String result = buf.toString();
System.err.println( "\nResponse from server after POST:\n" + result );
}
catch( Throwable t )
{
t.printStackTrace( System.out );
}
// Have done modification and added some lines in your code, hope it will work
URLConnection con = url.openConnection();
//Added this one to make your connection http
HttpURLConnection conn = (HttpURLConnection) con;
// con.connect();
// specify that we will send output and accept input
conn .setDoInput(true);
conn .setDoOutput(true);
conn .setRequestProperty("accept-charset", "UTF-8");
// tell the web server what we are sending
conn.setRequestProperty ( "Content-Type", "text/xml" );
// set data posting method
conn.setRequestMethod("POST");
// OutputStreamWriter writer = new OutputStreamWriter( conn.getOutputStream() );
PrintWriter writer = new PrintWriter(conn.getOutputStream());
writer.write( inputXML );
writer.close();
// reading the response
// InputStreamReader reader = new InputStreamReader( conn.getInputStream() );
BufferedInputStream reader = new BufferedInputStream(conn.getInputStream());
I am trying to write a code which will give me the contents of the page as the response in a string using GET method in java.
Below is the code I am using, its throwing me error that java.net.MalformedURLException: no protocol
If I try inserting http:// in starting of the URL its giving me Unknown Host Exception.
String request = ("http://gotoanswer.com/?q=What+is+the+Java+equivalent+for+the+following+in+curl%3F");
System.out.println(request);
URL url = null;
try{
new URL(request);
HttpURLConnection connection = (HttpURLConnection) new URL(request).openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestProperty("charset", "utf-8");
connection.connect();
Reader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
for ( int c = in.read(); c != -1; c = in.read() )
System.out.print((char)c);
}
catch(IOException e){
System.out.println(e);
}
NOT a duplicate of my other question.
I am sending a POST request like this:
String urlParameters = "a=b&c=d";
String request = "http://www.example.com/";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.disconnect();
How can I read the xml response returned from a HTTP POST request? Particularly, I want to save the response file as a .xml file, and then read it. For my usual GET requests, I use this:
SAXBuilder builder = new SAXBuilder();
URL website = new URL(urlToParse);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("request.xml");
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
fos.close();
// Do the work
Addendum: I'm using the following code and it works just fine. However, it neglects any spacing and new lines and treats the complete XML contents as a single line. How do I fix it?
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb1 = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb1.append(line);
}
FileOutputStream f = new FileOutputStream("request.xml");
f.write(sb1.toString().getBytes());
f.close();
br.close();
don't use Readers and readLine() with xml data. use InputStreams and byte[]s.
Thanks to Pangea, I modified his code and this now works:
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer t= transFactory.newTransformer();
t.setOutputProperty(OutputKeys.METHOD, "xml");
t.setOutputProperty(OutputKeys.INDENT,"yes");
Source input = new StreamSource(is);
Result output = new StreamResult(new FileOutputStream("request.xml"));
transFactory.newTransformer().transform(input, output);