Java Post Request Not Working - java

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.

Related

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

Posting to a webservice using httpurlconnection

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.

Unable to upload a document using HttpPost

I am trying to upload a document from my local machine to Http using following code but I am getting HTTP 400 Bad request error. My source data is in Json.
URL url = null;
boolean success = false;
try {
FileInputStream fstream;
#SuppressWarnings("resource")
BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\Users\\Desktop\\test.txt"));
StringBuffer buffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
buffer.append(line);
}
String request = "http://example.com";
URL url1 = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
connection.setDoOutput(true); // want to send
connection.setRequestMethod("POST");
connection.setAllowUserInteraction(false); // no user interaction
connection.setRequestProperty("Content-Type", "application/json");
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.flush();
wr.close();
connection.disconnect();
System.out.println(connection.getHeaderFields().toString());
// System.out.println(response.toString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Have a look into apache http libraries which will help a lot with that:
File file = new File("path/to/your/file.txt");
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://someposturl.com";
HttpPost post = new HttpPost(postURL);
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("myFile", bin);
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
The example above is taken from my blog and it should work with standard Java SE as well as Android.
The DataOutputStream is for writing primitive types. This causes it to add extra data to the stream. Why aren't you just flushing the connection?
connection.getOutputStream().flush();
connection.getOutputStream().close();
EDIT:
It also occurs to me that you've not actually written any of your post data, so you probably want a something more like:
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(buffer.toString());
wr.close();

Categories