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();
Related
I'm trying to create a client server application and I'm currently stuck. I have this java code on my client.
HttpURLConnection connection;
connection = (HttpURLConnection) new URL("http://www.masterpaint.gr/login.php").openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
connection.setRequestProperty("Accept","application/json: charset=UTF-8");
connection.setRequestMethod("POST");
System.out.println("The request method on client end is " + connection.getRequestMethod());
System.out.println("Server response to connection " + connection.getResponseMessage());
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String buffer;
StringBuilder stringBuilder = new StringBuilder();
while ((buffer = reader.readLine()) != null) {
stringBuilder.append(buffer);
}
System.out.println("The request methond on server end is " + stringBuilder.toString());
And this is the simple test php code on the server.
<?php echo $_SERVER['REQUEST_METHOD']; ?>
Whenever I run this test java program and try to connect I get the same output.
The request method on client end is POST
Server response to connection OK
The request methond on server end is GET
The php script always echoes back that I'm sending a GET request even though
my java code states that use a POST. I have tried connecting to the script through postman using different request methods and it's all fine, so the problem must be in the Java code. Any insight would be greatly appreciated.
I am not having any experience of php but it seems like it is looking for content-length header which will not be send in your case so it is treating this as GET request.
HttpURLConnection connection;
connection = (HttpURLConnection) new URL("http://www.masterpaint.gr/login.php").openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
connection.setRequestProperty("Accept","application/json: charset=UTF-8");
connection.setRequestMethod("POST");
connection.setFixedLengthStreamingMode(0);
System.out.println("The request method on client end is " + connection.getRequestMethod());
System.out.println("Server response to connection " + connection.getResponseMessage());
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String buffer;
StringBuilder stringBuilder = new StringBuilder();
while ((buffer = reader.readLine()) != null) {
stringBuilder.append(buffer);
}
System.out.println("The request methond on server end is " + stringBuilder.toString());
This will set content length 0 as you are not sending any content.
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 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.
I would like to capture an image from the camera on Android, and send it to Google App Engine, which will store the image in the blob store. Sounds simple enough, and I can get the multi-part POST to GAE happening, but storing to the Blob store requires the servlet return an HTTP redirect (302). So, I need a connection that can follow redirects after doing an HTTP POST. Here is the code I WISH would work:
public static String sendPhoto(String myUrl, byte[] imageData) {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String pathToOurFile = "/data/file_to_send.jpg";
String urlServer = myUrl;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
// Please follow redirects
HttpURLConnection.setFollowRedirects(true);
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
try {
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// I really want you to follow redirects
connection.setInstanceFollowRedirects(true);
connection.setConnectTimeout(10000); // 10 sec
connection.setReadTimeout(10000); // 10 sec
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
connection.connect();
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name="
+ "\"file1\";filename=\""
+ pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.write(imageData);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
outputStream.flush();
outputStream.close();
rd = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
}
Log.i("Response: ", sb.toString());
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i("Response: serverResponseCode:",
String.valueOf(serverResponseCode));
Log.i("Response: serverResponseMessage:", serverResponseMessage);
} catch (Exception ex) {
ex.printStackTrace();
}
}
As much as I try, this code will not follow redirects. The input steam is always empty, and the response is always 302. The image is uploaded nicely though. If someone could tell me what I can do to make it follow the redirect so I can read the response, I would really appreciate it.
Alternatively, if there is a better approach, I would love to hear it. I know there are libraries out there like Apache HTTP Client, but it requires so many dependencies that is seems like too much bloat for a simple task.
Thanks
A few months ago I was trying to do the exact same thing!
Basically, don't use HttpURLConnection. Instead, use HttpClient and HttpGet in the org.apache.http package which are part of the Android SDK.
Unfortunately I don't have my source code to provide an example, but hopefully that'll set you in the right direction.
not sure what went wrong, but you can follow redirect yourself. take the Location header out and make a new connection to it.