I need to send a post request to a https address. I have a function that sends post messages currectly but i cant seem to make it work for https.
public static String serverCall(String link, String data){
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = data;
try
{
url = new URL(link);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after process will be stored in response variable.
response = sb.toString();
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
}
return response;
}
i have tryed using HttpsURLConnection insted of HttpURLConnection, i am still getting null from my server.
you should call connect();
....
connection.setRequestMethod("POST");
connection.connect();
....
Related
How to call subsequent requests using j_security_check, I have followed below code but it's not working .
String url = "https://myhost/jsp/j_security_check?j_username=myuser&j_password=mypassword";
HttpURLConnection connection = (HttpURLConnection) new
URL(url).openConnection();
if (connection.getResponseCode() == 200) {
String cookie = connection.getHeaderField("Set-Cookie").split(";", 2)[0];
url = "https://myhost/getusers";
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("Cookie", cookie);
connection.setRequestProperty("Cache-Control", "no-cache");
InputStream input = connection.getInputStream();
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String result = buffer.lines().collect(Collectors.joining("\n"));
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
Can anyone help me on it.
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.
I am using Google Appengine Java endpoints with internal microservices(Modules).
When I execute a call from the endpoints to a module Servlet I receive the X-AppEngine-Inbound-AppId as per documentation(request.getHeader("X-Appengine-Inbound-Appid") and is all good.
When I try to call a module endpoint I don't receive it anymore!!
I am using the same code to execute all the HTTP requests.
public GenericResponse makePOSTRequest(String urlString, Object requestObject, String jSessionId, boolean parseSessionId) {
GenericResponse genericResponse;
String rawPayload = mJsonParser.toJson(requestObject);
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length", String.valueOf(rawPayload.getBytes("UTF-8").length));
if (jSessionId != null) {
connection.setRequestProperty("Cookie", "JSESSIONID=" + jSessionId);
}
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(rawPayload);
writer.close();
InputStreamReader isr = new InputStreamReader(connection.getInputStream(), "UTF-8");
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
if (!parseSessionId) {
genericResponse = new GenericResponse(connection.getResponseCode(), sb.toString());
} else {
String responseSessionId = parseSessionId(connection);
genericResponse = new GenericResponse(connection.getResponseCode(), sb.toString(), responseSessionId);
}
return genericResponse;
Following piece of code was working for the last three years, but all of a sudden it throws connection timed out only in server, but works as intended in localhost.
Any comments ?
public String getWikiContent(String query) {
StringBuilder builder = new StringBuilder();
String path = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro=1&explaintext=1&titles=" + query + "&format=json&redirects";
try {
URL url = new URL(path);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestProperty("Content-Type",
"application/json");
if (urlConn.getResponseCode() != 200) {
throw new IOException(urlConn.getResponseMessage());
}
InputStream is = urlConn.getInputStream();
BufferedReader buff = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = buff.readLine()) != null) {
builder.append(line);
}
}catch (IOException e){
e.printStackTrace();
}
return builder.toString();
}
For some reasons its a network issue, just adding a proxy server fixed it.
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url,port));
URLConnection urlConn = url.openConnection(proxy);
I used to use DefaultHttpClient for my networking code, but decided to change to HttpURLConnection.
I have searched for other questions on how to send POST messages (eg How to add parameters to HttpURLConnection using POST), but for some reason my Flask app always gives me error 400.
When I use logcat, it indeed displays that my POST message is "username=asdf&password=asdf". I include the code below. Also, if I initialized the cookieManager in the method that called this method (makeServiceCall), will returning cookieManager keep my session for subsequent calls to makeServiceCall?
public CookieManager makeServiceCall(CookieManager cookieManager, String urlString, int method, List<NameValuePair> db) {
String charset = "UTF-8";
try {
URL url = new URL(urlString);
if (method == POST) {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (db != null) {
try {
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Accept-Charset", charset);
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(out, charset));
Log.d("log", "> " + getQuery(db));
writer.write(getQuery(db));
writer.flush();
writer.close();
out.close();
//Get Response
InputStream in = urlConnection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
Log.d("Read attempt: ", "> " + response.toString());
}
finally {
urlConnection.disconnect();
}
}
}
etc.
Flask code:
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
flash('You were logged in')
return redirect(url_for('show_entries'))
return render_template('login.html', error=error)