I have a question how to implement a post request in java in android studio if I have a valid request using curl:
'curl.exe anyValidUrl -d "911/21.10.2020/15.45" -H "Content-Type: text/plain"'
When sending data to the server, error 500 takes off.
Most likely I am sending data in the wrong form, where am I wrong, please tell me.
The function in which I am sending data:
{
InputStreamReader isR = null;
BufferedReader bfR = null;
StringBuilder sbRes = new StringBuilder();
HttpURLConnection urlConnection = null;
String strBody = "911/21.10.2020/15.45";
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Length","" + Integer.toString(strBody.getBytes().length));
urlConnection.addRequestProperty("Content-Type","text/plain");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
wr.writeBytes(strBody);
wr.flush();
wr.close();
urlConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println( urlConnection.getRequestMethod());
if (HttpURLConnection.HTTP_OK == urlConnection.getResponseCode()) {
isR = new InputStreamReader(urlConnection.getInputStream());
bfR = new BufferedReader(isR);
String line;
while ((line = bfR.readLine()) != null) {
sbRes.append(line);
}
}
else{
return (String.valueOf(urlConnection.getResponseCode()));
}
return sbRes.toString();
}
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 new to programming in android, i wanted to get json data from the website https://api.clashofclans.com/v1/clans in my android app.
How can i request the data in json format
curl -X GET --header 'Accept: application/json' --header "authorization: Bearer " 'https://api.clashofclans.com/v1/clans' .
i dont know how to add api key in the combination and open network connection. thanks in advance.
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.addRequestProperty("Accept","application/json");
urlConnection.addRequestProperty("authorization","my api-key here");
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " +
urlConnection.getResponseCode());
}
i am getting "Error response code: 403", can u tell me where my code is wrong
the api key is based on ip address.
Im sending it to my method this is where i return it as String:
public void getJson() {
String json = getJSONFromURLConnection("https://api.clashofclans.com/v1/clans?name=illuminati");
if (json != null) {
Log.i("JSON", json.toString());
}
}
Here getting all info:
private String getJSONFromURLConnection(String urlString) {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
String apikey = YOUR_KEY;
urlConnection.setRequestMethod("GET");
urlConnection.addRequestProperty("Authorization", "Bearer " + apikey);
urlConnection.setRequestProperty("Accept", "application/json");
if (urlConnection.getResponseCode() == 200) {
InputStream stream = urlConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} else {
Log.e("Error", "Error response code: " +
urlConnection.getResponseCode());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
return null;
}
Created and tested, works for me hope you get the result you need.
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)
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();
....