I want to post an xml to another server - java

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());

Related

Android POST Request Not Working Properly

I am using the following method for getting time from server with a Post request.
String result = "";
URL url = null;
InputStream stream = null;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://192.168.118.2/myapi");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
String data = URLEncoder.encode("time", "UTF-8")
+ "=" + URLEncoder.encode("Submit", "UTF-8");
urlConnection.connect();
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data);
wr.flush();
stream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
String line = "";
while((line = reader.readLine()) != null)
result += line;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
Here is php script
<?php
if(isset($_POST["time"]))
echo "Time";
else
echo "Invalid Request";
But when i call post method, i get resut "Invalid Request".
I almost searched every stackoverflow threads but none of them working, i really wonder what is the problem.
A few things to try.
1) Add the following to your manifest.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
2) change your PHP file
<?php
$time = urldecode($_POST['time']);
if($time === NULL) {
echo "invalid";
} else {
echo "time";
}
?>
I fixed the problem with following changes;
data = "time=Submit";
...
...
...
url = new URL("http://192.168.118.2/myapi/index.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setInstanceFollowRedirects( false );
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty( "charset", "utf-8");
urlConnection.setRequestProperty( "Content-Length", Integer.toString( data.getBytes().length ));
urlConnection.setUseCaches( false );
urlConnection.setConnectTimeout(1000);
urlConnection.setReadTimeout(1000);
...
...
...

How to hit the multiple url within same session and with one authentication in java

I have to hit one rest url and before that i am hitting another rest url for loginn purposes by passing username/password. I am getting 200 OK from the first url. Now when i am trying to consume another REST url it's giving me 401 error.Code is as follows"
String urlParameters = "username=a&password=b&rememberme=false";
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
URL url = new URL("myloginurl");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("charset", "UTF-8");
con.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
con.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( con.getOutputStream())) {
wr.write( postData );
}
int respCode = con.getResponseCode();
if(respCode==200){
urlParameters = "id=x&col1=y&op1=z&val1=t";
postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
postDataLength = postData.length;
url = new URL("myanotherurl");
con.setDoOutput(true);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("charset", "UTF-8");
con.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
con.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( con.getOutputStream())) {
wr.write( postData );
}
System.out.println(con.getResponseCode());
}
Can anybody please point out where i am doing the mistake. Also let me know is there any better way to write this code.
Thanks
The server should return a session id in the form of a new cookie in your first request. You have to include that cookie in your second request, so that the server can identify you. The cookie is sent within the http headers.
After you get the responsecode from the first request, you can fetch the new cookie values like:
String cookieValue = con.getHeaderFields()
.getOrDefault("Set-Cookie", Collections.emptyList())
.stream()
.map(str -> str.split(";")[0])
.collect(joining("; "));
Then you use that value for the cookies in the next request like:
con.setRequestProperty("Cookie", cookieValue);

Unable to use GET Method

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);
}

Sending an HTTP POST request through the android emulator doesn't work

I'm running a tomcat servlet on my local machine and an Android emulator with an app that makes a post request to the servlet. The code for the POST is below (without exceptions and the like):
String strUrl = "http://10.0.2.2:8080/DeviceDiscoveryServer/server/devices/";
Device device = Device.getUniqueInstance();
urlParameters += URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(device.getUser(), "UTF-8");
urlParameters += "&" + URLEncoder.encode("port", "UTF-8") + "=" + URLEncoder.encode(new Integer(Device.PORT).toString(), "UTF-8");
urlParameters += "&" + URLEncoder.encode("address", "UTF-8") + "=" + URLEncoder.encode(device.getAddress().getHostAddress(), "UTF-8");
URL url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(urlParameters);
wr.flush();
wr.close();
Whenever this code is executed, the servlet isn't called. However if I change the type of the request to 'GET' and don't write anything to the outputstream, the servlet gets called and everything works fine. Am I just not making the POST correctly or is there some other error?
try the following code, it may help u
try
{
String argUrl =
"";
String requestXml = "";
URL url = new URL( argUrl );
URLConnection con = url.openConnection();
System.out.println("STRING" + requestXml);
// 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( requestXml );
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 );
}
Out of curiosity I tried getting the response code for my request:
int responseCode = connection.getResponseCode();
System.out.println(responseCode);
This actually made the request go through and I got 200. I checked my Tomcat logs and the request finally got handled. I guess doing url.openConnection() and writing to the OutputStream isn't enough.

Http client Post xml file in java

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));

Categories

Resources