Posting to a webservice using httpurlconnection - java

How come I am only allowed to make posts to .com url's but not .asmx url's? Im a bit confused as what I want to generally do is send xml content to a .asmx url web service eventually. Can anyone supply me with tips why this doesn't work, and how I can post to a .asmx file?
public class POSTSenderExample {
public String echoCuties(String query) throws IOException {
// Encode the query
String encodedQuery = URLEncoder.encode(query, "UTF-8");
// This is the data that is going to be send to itcuties.com via POST request
// 'e' parameter contains data to echo
String postData = "e=" + encodedQuery;
URL url = new URL("http://echo.itgeeeks.asmx");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(postData.length()));
// Write data
OutputStream os = connection.getOutputStream();
os.write(postData.getBytes());
// Read response
StringBuilder responseSB = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ( (line = br.readLine()) != null)
responseSB.append(line);
// Close streams
br.close();
os.close();
return responseSB.toString();
}
// Run this example
public static void main(String[] args) {
try {
System.out.println(new POSTSenderExample().echoCuties("Hi there!"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}

Using "POST" is correct.
Instead of calling
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
you have to call
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
(if you are using utf-8 encoding which is probably the case).
You also have to set the SOAP Action in the http- Header:
connection.setRequestProperty("SOAPAction", SOAPAction);
You can find the SOAP Action eihter in the wsdl- file. What I did to find out all expected Parameters: I used a working WS Client, and traced the TCP traffic in order to find out the expected HTTP headers.

Related

Send request body with GET request using HttpURLConnection in java

Kindly don't confuse my question with sending body with POST request using HttpURLConnection.
I want to send body with GET request using HttpURLConnection. Here is code i am using.
public static String makeGETRequest(String endpoint, String encodedBody) {
String responseJSON = null;
URL url;
HttpURLConnection connection;
try {
url = new URL(endpoint);
connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(true);
connection.setDoOutput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
OutputStream outputStream = connection.getOutputStream();
outputStream.write(encodedBody.getBytes());
outputStream.flush();
Util.log(connection,connection.getResponseCode()+":"+connection.getRequestMethod());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String responseChunk = null;
responseJSON = "";
while ((responseChunk = bufferedReader.readLine()) != null) {
responseJSON += responseChunk;
}
bufferedReader.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
Util.log(e, e.getMessage());
}
return responseJSON;
}
what happens is that the request type is identified automatically depending on the connection.getInputStream() and connection.getOutPutStream().
when you call connection.getOutPutStream() the request type is automatically set to POST even if you have explicitly set request type to GET using connection.setRequestMethod("GET").
The problem is that i am using 3rd party Web Service(API) which accepts request parameters as body with GET request
<get-request>
/myAPIEndPoint
body = parameter1=value as application/x-www-form-urlencoded
<response>
{json}
I am well aware that most of the case GET don't have request body but many of the web service often uses GET request with parameters as body instead of query string. Kindly guide me how i can send GET request with body in android without using any 3rd party library(OkHttp,Retrofit,Glide etc)
use this code you will need to do a little modification but it will get the job done.
package com.kundan.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class GetWithBody {
public static final String TYPE = "GET ";
public static final String HTTP_VERSION = " HTTP/1.1";
public static final String LINE_END = "\r\n";
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 8080); // hostname and port default is 80
OutputStream outputStream = socket.getOutputStream();
outputStream.write((TYPE + "<Resource Address>" + HTTP_VERSION + LINE_END).getBytes());//
outputStream.write(("User-Agent: Java Socket" + LINE_END).getBytes());
outputStream.write(("Content-Type: application/x-www-form-urlencoded" + LINE_END).getBytes());
outputStream.write(LINE_END.getBytes()); //end of headers
outputStream.write(("parameter1=value&parameter2=value2" + LINE_END).getBytes()); //body
outputStream.flush();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder builder = new StringBuilder();
String read = null;
while ((read = bufferedReader.readLine()) != null) {
builder.append(read);
}
String result = builder.toString();
System.out.println(result);
}
}
this the Raw HTTP Request Dump
GET <Resource Address> HTTP/1.1
User-Agent: Java Socket
Content-Type: application/x-www-form-urlencoded
parameter1=value&parameter2=value2
Note : This is for http request if you want https Connection Please refer to the link SSLSocketClient

How to follow redirect other link with server's post in spring

I'm connecting with two local servers post parameters for redirect link. But not change url and web view after posting the parameters. I get only response.toString() (html string like ...."). How I change redirect link and view.
I found other questions and answers that are not easy to understand.
try {
HttpURLConnection connection = null;
URL url = new URL("http://localhost:9090/myproject/payreq");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", ""
+ Integer.toString(postParams.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection
.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
I expect change my project link's 8080 from redirect follow other sites.
If you want to redirect to a different server, completetely on the server side, without the user noticing a change in the browser URL, use forward: redirection:
#Controller
public class MyController {
#RequestMapping("/myurl")
public String redirectWithUsingForwardPrefix(ModelMap model) {
model.addAttribute("attribute", "forwardWithForwardPrefix");
return "forward:/http://localhost:9090/myproject/payreq";
}
}

Malformed request exception when trying to send GET request

I'm trying to connect to GDAX using their REST API.
I first want to do something very simple, i.e. getting historic rates.
I tried this:
private static final String GDAX_URL = "https://api.gdax.com";
public String getCandles(final String productId, final int granularity) {
HttpsURLConnection connection = null;
String path = "/products/" + productId + "/candles";
try {
//Create connection
URL url = new URL(GDAX_URL);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("granularity", String.valueOf(granularity));
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(path);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
But I get a 400 code in return "Bad Request – Invalid request format".
My problem is with the passing of the path "/products//candles" and the parameters (e.g. granularity).
I don't understand what should go in the request properties and in the message itself, and in what form.
I managed to make it work like this:
URL url = new URL(GDAX_URL + path + "?granularity="+granularity);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
Not sure how to use the DataOutputStream, so I just removed it. At least it works.

HTTPServer Post parameters [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Am writing a service using the HTTPServer provided by com.sun.net.httpserver.HttpServer package. I need to send some sizable data as a byte stream to this service (say a million integers).
I have almost searched all the examples available, all point to sending a small GET request in the URL.
I need to know how to send the data as a POST request.
Also is there any limit on the data that can be sent?
Rather than persistent URL connection in the answer above, I would recommend using Apache HTTPClient libraries (if you are not using Spring for applet-servlet communication)
http://hc.apache.org/httpclient-3.x/
In this you can build a client and send a serialized object (for instance serialised to JSON string: https://code.google.com/p/google-gson/ ) as POST request over HTTP to your server:
public HttpResponse sendStuff (args) {
HttpPost post = null;
try {
HttpClient client = HttpClientBuilder.create().build();
post = new HttpPost(servletUrl);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(<nameString>, <valueString>));
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
response.getStatusLine().getStatusCode();
return response;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
However Spring saves you a lot of time and hassle so I would recommend to check it out
You can send the data for the POST request by writing bytes to the connections output stream as shown below
public static String excutePost(String targetURL, String urlParameters)
{
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
With POST, there is no limit on the amount of data that can be sent. You can find out the details about the limitations of GET here maximum length of HTTP GET request?
If I got you right, you want to send requests in direction of your HTTPServer, as a GET request instead of using post.
In your HTTP Client implementation you can set the HTTP Headers and also the request Method:
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("GET"); //Or POST
} catch (IOException e) {
e.printStacktrace();
}

Java Post Request Not Working

Why does this not work? I have also tried using HttpURLConnection class however this did not work either. The php page cannot find the posted data.
Note: im new to post requests with java.
public static String GetURL(String inUrl, String post) {
String inputLine = "";
try {
if (!inUrl.contains("http")) {
throw new Exception("Invalid URL");
} else {
Log.writeLog(inUrl);
URL url = new URL(inUrl);
//send post
URLConnection connection = url.openConnection();
//connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.connect();
OutputStream wr = connection.getOutputStream();
wr.write(post.getBytes());
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
inputLine = in.readLine();
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
Log.writeLog("Error getting url.");
}
return inputLine;
}
Since you didn't specify the error, it is hard for me to see where you went wrong.
However, I think it would be a lot easier to use an abstraction like HttpClient. Your code would look like this:
URI uri = new URIBuilder()
.setURI(inUrl)
.addHeader("Accept-Charset", "UTF-8")
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(post);
Much cleaner than dealing with the low-level details of streams and connections.

Categories