How can i use "sendPost Function", Instead of using more than one "sendPost function" for different requests in NodeJs ?
like this Example,I do 2 sendPost function to send 2 requests.
But the code itself is in the two functions with little change, so I want a way to do one "sendPost" function for both requests.
////////sign up
public static void sendPOST1(String POST_PARAMS) throws Exception {
System.out.println("Sending http");
URL obj = new URL(POST_URL_SU);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json");
con.setConnectTimeout(50000); // 5 seconds
con.setReadTimeout(50000); // 5 seconds
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
byte[] outputBytesArray = POST_PARAMS.getBytes();
os.write(outputBytesArray);
os.flush();
os.close();
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
// Here it read line line
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Res: " + response.toString());
} else {
System.out.println(con.getResponseMessage());
System.out.println("POST request not worked");
}
}
////////Login
public static void sendPOST2(String POST_PARAMS) throws Exception {
System.out.println("Sending http");
URL obj = new URL(POST_URL_LI);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json");
con.setConnectTimeout(50000); // 5 seconds
con.setReadTimeout(50000); // 5 seconds
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
byte[] outputBytesArray = POST_PARAMS.getBytes();
os.write(outputBytesArray);
os.flush();
os.close();
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader 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("Res: " + response.toString());
} else {
System.out.println(con.getResponseMessage());
System.out.println("POST request not worked");
}
}
You can create a single function sendPost() that takes a URL parameter:
public static void sendPost(String url, String POST_PARAMS) throws Exception {
System.out.println("Sending http");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json");
con.setConnectTimeout(50000); // 5 seconds
con.setReadTimeout(50000); // 5 seconds
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
byte[] outputBytesArray = POST_PARAMS.getBytes();
os.write(outputBytesArray);
os.flush();
os.close();
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader 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("Res: " + response.toString());
} else {
System.out.println(con.getResponseMessage());
System.out.println("POST request not worked");
}
}
In fact, I suggest you break this function into several smaller functions that do simple tasks.
Related
I am hitting below url using any rest client and I get the api Response :400 Bad Request with response body
INPUT param
POST http://SOME.IP:8008/equipment_api/F0-03-8C-C3-D3-CC/832
HEADERS
Content-Type application/json
X-RequestID 1234
BODY
{
"items":[{"updateValue":1, "updateKey": "RESETDEV"}],
"sync":"false"
}
Response :400 Bad Request
{
"error": "RESETDEV is not a valid key."
}
But java simple client does not show the response body.. below is java code.. it just give 400 bad req.
public static void main(String[] args) {
try {
String urlParameters = " {\r\n" +
"\"items\":[{\"updateValue\":\"Hi\", \"updateKey\": \"RESETDEV\"}],\r\n" +
"\"sync\":false\r\n" +
"}";
URL url = new URL("http://SOME.IP:8008/equipment_api/F0-03-8C-C3-D3-CC/832");
URLConnection conn = url.openConnection();
conn.setRequestProperty("content-type", "application/json");
conn.setRequestProperty("X-RequestID", "1234");
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
}catch(Exception ex) {
System.out.println("some error :: "+ex.toString());
}
}
Try to use following code
final String uri = "http://SOME.IP:8008/equipment_api/F0-03-8C-C3-D3-CC/832";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("X-RequestID", "1234");
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
System.out.println(result);
Wrap with Try Catch.
May it is useful to you. It will work
public static void main(String[] args) {
try {
String urlParameters = " {\r\n" +
"\"items\":[{\"updateValue\":\"Hi\", \"updateKey\":
\"RESETDEV\"}],\r\n" +
"\"sync\":false\r\n" +
"}";
URL url = new URL("http:http://SOME.IP:8008/equipment_api/F0-03-
8C-C3-D3-CC/832");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("content-type", "application/json");
con.setRequestProperty("X-RequestID", "1234");
con.setDoOutput(true);
OutputStreamWriter writer = new
OutputStreamWriter(con.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
//BufferedReader reader = new BufferedReader(new
InputStreamReader(con.getInputStream()));
InputStream is = con.getInputStream();
if(con.getResponseCode() >= 200 && 299 <= con.getResponseCode()) {
is = con.getInputStream();
}else {
is = con.getErrorStream();
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(is,
"utf-8"))) {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
writer.close();
// br.close();
}catch(Exception ex) {
System.out.println("some error :: "+ex.toString());
}
}
I'm using the code below to create a http request to my amazon AWS api gateway with an object (mp3Base64) as its content. However, it needs to have the authorization token attached. Can anyone explain how this is done and show an example? Any help is gratefully received. Thanks.
public String executePost(String targetURL, Mp3Base64 mp3Base64) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String mp3Base64Json = mapper.writeValueAsString(mp3Base64);
URL obj = new URL(targetURL);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
connection = (HttpURLConnection) obj.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
Integer.toString(mp3Base64Json.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes("base64=" + mp3Base64Json);
wr.flush();
wr.close();
//Get Response
int responseCode = connection.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + targetURL);
System.out.println("Post parameters : base64 =" + mp3Base64Json);
System.out.println("Response Code : " + responseCode);
InputStream is = connection.getInputStream();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
return response.toString();
}
I have this method to connect to my webservice (REST API)
public static void getHttpCon() throws Exception{
String tokenUrl = AppPropertiesService.getProperty( URL_TOKEN );
String username = AppPropertiesService.getProperty( USERNAME );
String password = AppPropertiesService.getProperty( PASSWORD );
String POST_PARAMS = "username="+username+"&password="+password+"&lang=fr&grant_type=password&client_id=apiclient";
URL obj = new URL(tokenUrl);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json;odata=verbose");
con.setRequestProperty("Authorization",
"Basic Base64_encoded_clientId:clientSecret");
con.setRequestProperty("Accept",
"application/x-www-form-urlencoded");
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
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());
} else {
System.out.println("POST request not worked");
}
}
I want to know how can i POSTa CSV File .
Should I do it directly in my method above ?
Do I have to create a new method by recovering the connection token from my method above?
My API ULR is POST /api/{id}/csv
I am facing a problem while using POST Method in Java nowadays. I am receiving
Exception in thread "main" java.lang.RuntimeException: Server returned HTTP response code: 411 for URL.
I couldn't find any available document anywhere. None of them were useful. How do I fix it?
My code
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class req {
public static void main(String[] args) {
sendPostRequest(requestURL);
}
private static String sendPostRequest(String requestUrl) {
StringBuilder jsonString = new StringBuilder();
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
byte[] data = requestUrl.getBytes("UTF-8");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("Content-Length", String.valueOf(data.length));
connection.setRequestProperty("Authorization", "Basic " + "usename:password");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return jsonString.toString();
}
}
Perfectly working method:
public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = br.readLine();
}
else {
response="Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
If you are returning a JSON in your response:
public JSONObject getPostResult(String json){
if(!json.isEmpty()) {
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON_ERROR", "Error parsing data " + e.toString());
}
}
return jObj;
}
If you are still having trouble, maybe this will help. I did not test, machine does not have java installed.
You should also set all other headers that you need.
public static String PostRequest(String requestUrl, String username, String password) {
StringBuilder jsonString = new StringBuilder();
HttpURLConnection connection = null;
try {
URL url = new URL(requestUrl);
connection = (HttpURLConnection)url.openConnection();
byte[] authData = Base64.encode((username + password).getBytes());
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", "Basic " + new String(authData));
connection.setRequestProperty("Content-Length", String.valueOf(authData.length));
try (DataOutputStream writer = new DataOutputStream(connection.getOutputStream())) {
writer.writeBytes("REPLACE ME WITH DATA TO BE WRITTEN");
writer.flush();
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String data = null;
while ((data = reader.readLine()) != null) {
jsonString.append(data);
}
}
} catch (IOException ex) {
//Handle exception.
} finally {
if (connection != null)
connection.disconnect();
}
return jsonString.toString();
}
You should send empty data in body if you are using post method.
For example if you are using json data you need to send "{}"
public void Post() throws Exception {
StringBuffer d = new StringBuffer();
String da = "ClearanceDate=2020-08-31&DepositeDate=2020-08-31&BankTransactionNo=UATRYU56789";
URL url = new URL("https://abcd/AddReceipt?" + da);
byte[] postDataBytes = ("https://abcd/AddReceipt?" + da).toString()
.getBytes("UTF-8");
System.out.println("Data--" + postDataBytes);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
// con.setRequestProperty("User-Agent",
// "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length",
String.valueOf(postDataBytes.length));
con.setRequestProperty(
"Authorization",
"Bearer "
+ "o731WGgp1d913ZOYivnc55yOg0y1Wk7GsT_mnCUKOJf1VChYOdfRjovAxOhyyPKU93ERue6-l9DyG3IP29ObsCNTFr4lGZOcYAaR96ZudKgWif1UuSfVx4AlATiOs9shQsGgb1oXN_w0NRJKvYqD0LLsZLstBAzP1s5PZoaS9c6MmO32AV47FUvxRT6Tflus5DBDHji3N4f1AM0dShbzmjkBCzXmGzEDnU6Jg1Mo5kb884kParngKADG5umtuGbNzChQpMw_A0SyEYaUNh18pXVmnNhqM3Qx5ZINwDEXlYY");
con.setRequestProperty("Accept", "application/json");
con.setDoInput(true);
con.setDoOutput(true);
con.getOutputStream().write(postDataBytes);
int status = con.getResponseCode();
System.out.println("Response status: " + status + "|"
+ con.getResponseMessage());
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
con.disconnect();
System.out.println("Response status: " + status);
System.out.println(content.toString());
System.out.print("Raw Response->>" + d);
}
whenever I try to login to a website on my app I recieve a 400 BadRequest error. But when I do the same with a normal javaprogramm it works fine.
The login-methode:
public void sendPost(String url, String postParams) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host", "www.XXX.de");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Referer", "https://XXX.de/YYY/");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
conn.setDoOutput(true);
conn.setDoInput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
Log.w("App", "sendPost: ResponseCode: " + conn.getResponseCode());
responseCode = conn.getResponseCode();
james.setResponseCode_SendPost(responseCode);
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} // end of sendPost
Before I start sendPost() I always download at first the page (without BadRequest):
public String getPageContent(String url) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
conn.setHostnameVerifier(hostnameVerifier);
conn.setRequestMethod("GET");
conn.setUseCaches(false);
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
if (cookies != null) {
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
james.setResponseCode_GetPageContent(conn.getResponseCode());
int x = conn.getResponseCode();
Log.w("App", "ResponseCode: " + x);
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine + "\r\n");
}
in.close();
setCookies(conn.getHeaderFields().get("Set-Cookie"));
return response.toString();
} // end of getPageContent
I found the mistake by myself
The OutputStream method writeBytes() has to be
wr.writeBytes("request=" + postParams);
instead of
wr.writeBytes(postParams);