Why does HttpURLConnection not send the HTTP request - java

I would like to open an URL and submit the following parameters to it, but it only seems to work if I add the BufferedReader to my code. Why is that?
Send.php is a script what will add an username with a time to my database.
This following code does not work (it does not submit any data to my database):
final String base = "http://awebsite.com//send.php?";
final String params = String.format("username=%s&time=%s", username, time);
final URL url = new URL(base + params);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Agent");
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
But this code does work:
final String base = "http://awebsite.com//send.php?";
final String params = String.format("username=%s&time=%s", username, time);
final URL url = new URL(base + params);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Agent");
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
connection.disconnect();

As far as I know. When you called the connect() function, it will only create the connection.
You need to at least call the getInputStream() or getResponseCode() for the connection to be committed so that the server that the url is pointing to able to process the request.

Related

HttpsURLConnection - Send POST request

I want to send a POST request to this particular API: https://developer.lufthansa.com/docs/read/api_basics/Getting_Started and I researched how to do that and tried everything but it simply doesn't work, I always get an HTTP 400 or an HTTP 401 error. Here's my code:
private void setAccessToken(String clientID, String clientSecret) {
try {
URL url = new URL(URL_BASE + "oauth/token");
String params = "client_id=" + clientID + "&client_secret=" + clientSecret + "&grant_type=client_credentials";
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
osw.write(params);
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
} catch(IOException e) {
e.printStackTrace();
}
}
Kenta1561
Seems that your code is working well and it may be the case that you are providing invalid clientID or clientSecret so that your are getting wrong response in this case (as 401 indicates unauthorized). One thing you can do is you are only getting the response message if the http request status is ok (200). You may also get the invalid response message in case of 400 or 401 http response status. In order to print the invalid response messages you may follow the code below:
private void setAccessToken(String clientID, String clientSecret) throws Exception {
String params = "client_id=" + clientID + "&client_secret=" + clientSecret + "&grant_type=client_credentials";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
BufferedReader in;
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
if (responseCode >= 400)
in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
else
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
In this way you can also get invalid response message. In your case when I tried to hit the provided api it is giving me the response below:
{"error": "invalid_client"}

Java code to login to website which contains emailId in page and password in another page

I want to write a Java application, which can login to a website For example, www.tumblr.com/login. Basically this web page asks for an email address on the first page and then would take the user to the next page to enter the password.
Can someone please help me with a sample Java code for this problem?
You might want to look at HttpURLConnection
public static String executePost(String targetURL, String urlParameters) {
HttpURLConnection connection = null;
try {
//Create connection
URL 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.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
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();
}
}
Code example found here

Java httpserver crashes upon receiving POST requests

I am trying to write a simple HTTP server in Java that can handle POST requests. While my server successfully receives the GET, it crashes on the POST.
Here is the server
public class RequestHandler {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/requests", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
String response = "hello world";
t.sendResponseHeaders(200, response.length());
System.out.println(response);
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
And here is the Java code I use to send the POST
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://localhost:8080/requests";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
Each time the POST request crashes on this line
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
but when I change the URL to the one provided in the example where I found this it works.
Instead of
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
Use
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
You are connecting to a URL which is not HTTPS. When you call obj.openConnection(), it decides whether the connection is HTTP or HTTPS, and returns the appropriate object. When it's http, it won't return an HttpsURLConnection, so you cannot convert to it.
However, since HttpsURLconnection extends HttpURLConnection, using HttpURLConnection will work for both http and https URLs. The methods that you are calling in your code all exist int the HttpURLConnection class.

Address validation using geocode (GoogleMapAPI) in java

URL url = new URL("http://maps.google.com/maps/api/geocode/json?address=1600%20Amphitheatre%20Parkway&sensor=false&client_id=my_client_id&key=my_key");
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
InputStream in = httpURLConnection.getInputStream();
Its giving connection refused exception.
You forgot to actually connect:
URL url = new URL("yoururl");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
try {
// open the connection and get results as InputStream.
httpURLConnection.connect();
InputStream in = httpURLConnection.getInputStream();;
// do more things
} finally {
httpURLConnection.disconnect();
}
Also you can modify how you encode your URL to avoid errors:
private String REQUEST_URL = "http://maps.google.com/maps/api/geocode/json";
private String address = "1600 Amphitheatre Parkway";
URL url = new URL(REQUEST_URL + "?address=" + URLEncoder.encode(address, "UTF-8") + "&sensor=false&client_id=my_client_id&key=my_key"););

Server returned HTTP response code: 403 for URL:(How do I fix this?)

I keep keep getting the above error when I run the code below. All signs point to a problem with COOKIES from what I've read. If I am correct,how would I go about Implementing the CookieManager to fix this issue? Or how would I fix the issue if it is not an issue with COOKIES?
public class Client {
public Client(){
}
String executePost(String targetURL, String urlParameters){
URL url;
HttpURLConnection connection = null;
try{
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setChunkedStreamingMode(0);
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 dataout = new DataOutputStream(connection.getOutputStream());
dataout.writeBytes(urlParameters);
dataout.flush();
dataout.close();
//get response
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = br.readLine()) != null){
response.append(line);
response.append('\n');
}
System.out.println(response.toString());
br.close();
return response.toString();
}catch(Exception e){
System.out.println("Unable to full create connection");
e.printStackTrace();
return null;
}finally {
if(connection != null) {
connection.disconnect();
}
}
}
}
I removed : connection.setChunkedStreamingMode(0); and the code worked as it should
String executePost(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-Language", "en-US");
connection.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//send Request
DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
dataout.writeBytes(urlParameters);
dataout.flush();
dataout.close();
//get response
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = br.readLine()) != null){
response.append(line);
response.append('\n');
}
System.out.println(response.toString());
br.close();
return response.toString();
}catch(Exception e){
System.out.println("Unable to full create connection");
e.printStackTrace();
return null;
}finally {
if(connection != null) {
connection.disconnect();
}
}
}
A 403 response means "forbidden".
All signs point to a problem with COOKIES from what I've read. If I am correct,how would I go about Implementing the CookieManager to fix this issue? Or how would I fix the issue if it is not an issue with COOKIES?
It is not as simple as that.
It may be that you need to supply valid credentials (in the form of cookies, basic auth headers, or something else). However, you expect the server to respond with a 401 in that case, or a 302 to redirect your browser the a login page.
It may also be that you've supplied credentials, and they are not sufficient for the request you are trying to perform.
Your best bet is to figure out exactly what is happening when you try to login and use the service from your web browser. Then try to replicate that. Alternatively, read the site documentation or ask the site admins what to do.
If it is your site / server that you are trying to access, then you need to figure out how security is implemented. Perhaps you've misconfigured the server, or neglected to set up / enable login.
It is unlikely (IMO) that you will solve this problem by just setting up a Cookie Manager.
If you see the API documentation of setChunkedStreamingMode, it has been mentioned there that not all servers support this mode. Are you sure that the server you are making a connection to supports this ?

Categories

Resources