Send post data from android - java

I'm sending a POST request to certain server.
I can send the date from curl like this:
curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST https://ictexpo.herokuapp.com/users -d "{\"user\":{\"name\":\"Choity\"}}"
But when I want to send the same data from java I don't get the outcome.
String urlParameters = "{\"user\" : {\"name\" : \"lssl\" }}";
URL url2 = new URL(url);
HttpsURLConnection connection = (HttpsURLConnection) url2.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept","application/json");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(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();
Can anyone please tell me why I'm getting exceptopn?

Related

send file as a data binary to http post spring boot

I have a curl command:
curl -X POST "https:example.com/upload" -H "accept: application/json" -H "Authorization: token" -H
"Content-Type: text/plain" --data-binary #"filename.txt"
this is the code so far:
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
URL url = new URL("https://example.com/upload");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setSSLSocketFactory(sslsocketfactory);
conn.setRequestMethod("POST");
conn.setRequestProperty("accept", "application/json");
conn.setRequestProperty("Authorization", encodedValue);
conn.setRequestProperty("Content-Type", "text/plain");
OutputStream os = new BufferedOutputStream(conn.getOutputStream());
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
os.write(bytes);
os.flush();
int respCode = conn.getResponseCode();
System.out.println(respCode);
if (conn.getResponseCode() != 404) {
InputStream inputstream = conn.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
while ((client = bufferedreader.readLine()) != null) {
response.getWriter().println(client);
}
}
I am getting a 404 response.
can someone help me what am I doing wrong here? Please and thanks.

HttpUrlConnection Bad Request

I'm trying to use HttpUrlConnection to send a POST. Everything seems fine but it keeps returns 400, as if the parameters are not sent in the DataOutputStream, or anyway sent in a malformed way.
public String doDBAuth(String dbURL, String dbUser, String dbPassword) throws IOException {
HttpURLConnection connection = null;
String res = null;
try {
BufferedReader reader;
StringBuffer buffer;
URL url = new URL(dbURL + "/auth");
connection = (HttpURLConnection) url.openConnection();
String urlParameters = "username=actn-admin&password=Test#&cliend_id=admin-cli&grant_type=password";
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8 );
int postDataLength = postData.length;
connection.setRequestMethod("POST");
connection.setReadTimeout(40000);
connection.setConnectTimeout(40000);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
connection.setDoInput(true);
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
wr.writeBytes(urlParameters);
wr.flush();
}
int responseCode = connection.getResponseCode();
int status = connection.getResponseCode();
InputStream inputStream;
if (status == HttpURLConnection.HTTP_OK) {
inputStream = connection.getInputStream();
} else {
inputStream = connection.getErrorStream();
}
reader = new BufferedReader(new InputStreamReader(inputStream));
buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
res = buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
This is what is returned:
{"error":"unauthorized_client","error_description":"INVALID_CREDENTIALS: Invalid client credentials"}
This is weird cause this curl works properly:
curl --location --request POST '<URL>/auth' \
> --header 'Content-Type: application/x-www-form-urlencoded' \
> --data-urlencode 'username=actn-admin' \
> --data-urlencode 'password=Test#' \
> --data-urlencode 'client_id=admin-cli' \
> --data-urlencode 'grant_type=password' -k
and it returns me the access token I'm expecting
Keys and values need to be URL encoded (here's the spec).
Replacing "Test#" with "Test%40" should be enough in your example. For a future-proof solution you should encode all keys and values (e.g. with URLEncoder)

Java HTTP POST request code equivalent to curl call

curl -X POST --header "Content-Type: text/plain" --header "Accept: application/json" -d "HELLO THERE" "http://localhost:8080/rest/items/Echo_Living_Room_TTS"
I want to write Java code that does the same thing as this curl invocation. Here's what I've written so far:
URL myurl =new URL("http://localhost:8080/rest/items/Echo_Living_Room_TTS");
HttpURLConnection connection = (HttpURLConnection) myurl.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","text/plain");
connection.connect();
String urlParameters = "HELLO THERE";
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
if(something happens) {
try( DataOutputStream wr = new DataOutputStream( connection.getOutputStream())) {
wr.write( postData );
}
}
connection.disconnect();
Have I done it right? Are there any mistakes or omissions?
Ok seems like I made it works:
URL myurl =new URL("http://localhost:8080/rest/items/Echo_Living_Room_TTS");
HttpURLConnection connection = (HttpURLConnection) myurl.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","text/plain");
connection.setRequestProperty("Accept","application/json");
String mystring = "whatever";
byte[] postData = mystring.getBytes( StandardCharsets.UTF_8 );
int lenght = postData.length;
connection.setFixedLengthStreamingMode(lenght);
connection.connect();
try(OutputStream os = connection.getOutputStream()) {
os.write( postData );
}
connection.disconnect();
thank you all

Pass json object by navigator instead of java

I have a java application with this code :
URL url = new URL("http://myurl/");
HttURLConnection connection = (HttURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutplut(true);
connection.setRequestProperty("Content-Type", "application/json");
BufferedWriter buffer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
buffer.write("{\"foo:\"0}");
buffer.flush();
I just want to do the samething in my navigatour URL bar.
Edit
I found a tool to modifier headers. Here a screenshoot of the dev tool when I load my page.
Now where did I put my Json object?
If you need to send JSON data to your URL your code should be like this,
URL url = new URL("http://myurl/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
String input = "{\"foo\":\"bar\"}";
OutputStream ous = con.getOutputStream();
ous.write(input.getBytes());
ous.flush();
if (con.getResponseCode() != HttpURLConnection.HTTP_OK)
{
throw new RuntimeException("Failed : HTTP error code : " + con.getResponseCode());
}else
{
BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null)
{
System.out.println(output);
}
}
con.disconnect();
If you need GET Method then you can place this,
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
If you need to send Request Body with the URL you can use CURL. And also you can use POSTMAN. By using this you can send requests and receive the response.
CURL will be like this,
curl -v -H "Content-Type: application/json" -X POST \
-d '{\"foo\":\"bar\"}' http://myurl/
You can use Firefox to perform what you need, Read the 2nd answer.

return StringBuffer array

I'm using StringBuffer to send and receive variables from a web service.
My code is:
// Create connection
url = new URL(urlSCS + "/login");
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", "pl-PL");
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();
How can I change this code to be able to receive Array instead of String?
The request which I get from the web service is like this: {"var", "var"}.
This might help
http://www.coderanch.com/t/393008/java/java/explode-Java
Remember to cut the response from {} using response.substring()!
look at:
String partsColl = "A,B,C";
String[] partsCollArr;
String delimiter = ",";
partsCollArr = partsColl.split(delimiter);
you will have your responses in "" so substring them then.
Good luck!

Categories