An API is sending a large amount of data in the body in form of GZIP, I need to create rest API to decrypt and save it in the database, but I am not able to decrypt the data.
`#GetMapping
public void hello() throws IOException {
String payload = "{\n" +
" \"name1\": \"shrikant\",\n" +
" \"date\": \"Fri Apr 05 15:48:59 IST 2019\"\n" +
"}";
String urlStr = "http://localhost:8080/hello";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(60000);
conn.setConnectTimeout(60000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
conn.addRequestProperty("Content-Encoding", "gzip");
OutputStream os = conn.getOutputStream();
GZIPOutputStream gos = new GZIPOutputStream(os);
gos.write(payload.getBytes(StandardCharsets.UTF_8));
System.out.println("payload " +
Arrays.toString(payload.getBytes(StandardCharsets.UTF_8)));
os.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
}`
API to receive the data.
#PostMapping("hello")
public byte[] hello1(HttpServletRequest request) throws IOException {
System.out.println("hi");
ByteArrayInputStream bis = new ByteArrayInputStream();
GZIPInputStream gis = new GZIPInputStream(bis);
BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
sb.append(line);
}
}
but not able to decrypt data.
how to decrypt request.
On the client side you should close GZIPOutputStream before closing OutputStream.
gos.close();
os.close();
On the server side you should use InputStream from request
ServletInputStream inputStream = request.getInputStream();
GZIPInputStream gis = new GZIPInputStream(inputStream);
BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
For streams better use try-with-resources blok you won't have to remember about closing streams.
try (OutputStream os = conn.getOutputStream()) {
try (GZIPOutputStream gos = new GZIPOutputStream(os)) {
gos.write(payload.getBytes(StandardCharsets.UTF_8));
}
}
Related
I am using the below Java code to download the response from SOAP API. Soap API response contains Binary Data stream file. I am able to get the whole response with Binary data. I would need to download only Binary attachment file alone from Soap API.
Output:
enter image description here
Java code
String url = "https://services-sd02.drivecam.com/DCSubmission/EventFileStreamingService.svc";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "text/xml");
con.setRequestProperty("SOAPAction",
"http://DriveCam.com/Services/IEventFileStreamingService/GetEventFileById");
String xml = "Input Xml";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(xml);
wr.flush();
wr.close();
String responseStatus = con.getResponseMessage();
System.out.println(responseStatus);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String responseString = response.toString();
String out = responseString;
byte[] stream = out.getBytes();
FileOutputStream out1 = new FileOutputStream("P:/Informatica/data/zd_misc/TgtFiles/Binary_File");
out1.write(stream);
out1.close();
}
}
I'm sending an html request that will be used to send an email.
I would like to send an exe file in the json that will be attached to the email as well.
is it possible to do that?
URL url = new URL (url);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
String jsonInputString = "{\r\n" +
" \"emailaddress\":\"user#mail.com\",\r\n" +
" \"emailSubject\": \"hello\",\r\n" +
" \"emailBody\": \"Hello from Microsoft Flow triggered by java\"\r\n" +
"}";
System.out.println(jsonInputString);
try(OutputStream os = con.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
try(BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
this html request serves as a trigger for a flow in power automate
I'm trying to use glot.io api to compile java code with curl.
I read a text file :
BufferedReader bufferedReader = new BufferedReader(new FileReader("input.txt"));
StringBuffer stringBuffer = new StringBuffer();
String line = bufferedReader.readLine();
while(line != null){
stringBuffer.append(line);
line = bufferedReader.readLine();
}
If I use no quotation marks, I have no problem when I request the url
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty ("Authorization", "Token myToken");
conn.setRequestProperty("Content-Type", "application/json");
String data = "{\"files\": [{\"name\": \"main.java\", \"content\": \"" + stringBuffer.toString() + "\"}]}";
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(data);
out.close();
BufferedReader bf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
System.out.println(bf.readLine());
But when I use String in my code, the web page return 400 error.
Can you help me ?
I am really stuck on this problem and hoping for some help. I automatically log in to a Server and download a Excel (xlsx) File. The download seems to work fine, cause the size is the same as on the server and if I open the file with an XML-Editor it looks valid (compared to other excel Files).
But if I try to open the downloaded file with excel I got a "The file might be corrupt" message and it's not readable.
I tried to change the encoding of the file, the headers of the GET-Request, even tried to write it as Bytestream. Nothing changed.
Here are some relevant code snippets:
public HttpsURLConnection login()
{
HttpsURLConnection connection = null;
String user = "user";
String password = "password";
String authString = user + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
try {
connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
connection.setRequestProperty("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//connection.setRequestProperty("Content-Type", "application/vnd.openxml");
connection.setRequestProperty("Accept", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//connection.setRequestProperty("Accept", "application/vnd.openxml");
connection.setRequestProperty("User-Agent", USER_AGENT);
connection.connect();
} catch (IOException e)
{
e.printStackTrace();
}
return connection;
}
The download class
private void sendGet(HttpsURLConnection con) throws Exception {
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
String fileName = "test.xlsx";
file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
//use FileWriter to write file
FileWriter fw = new FileWriter(file.getAbsoluteFile());
//BufferedWriter bw = new BufferedWriter(fw);
/**CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
encoder.onMalformedInput(CodingErrorAction.REPORT);
encoder.onUnmappableCharacter(CodingErrorAction.REPORT);**/
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileName), "UTF-8"
));
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
bw.write(inputLine);
}
in.close();
bw.close();
//print result
//System.out.println(response.toString());
}
You can see my attempts in some of the commented lines.
I appreciate any help. Thanks in advance.
Hello I was wondering if somebody could help me with the following, I have a database that is currently populated. I used to call it using the http client and it worked fine but now I'm trying to update the code since its been deprecated to use the httpurlconnection but i have no success. I ve looked up some tutorials and tried a few thing but it doesn't seem to be working. the database is called through a php file and returns it in a json format.If i were to call the php file from my browser the response is the following: [{"id":"15","logo":"logo url","title":"title"}]
The error that I get on the console is the following:java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.InputStream.close()' on a null object reference
Which its not making much sense to me since the script pulls information
I have the following code, i left the commented section just in case i need any of it, It also includes the old way i used to call the DB Thank you!:
public void loadNews(){
InputStream is = null;
String result = "";
ArrayList<NameValuePair>();
try {
URL url = new URL("http://databasecall.php");
//HttpClient httpclient = new DefaultHttpClient();
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setRequestProperty("Content-length", "0");
//urlConnection.setUseCaches(false);
//urlConnection.setAllowUserInteraction(false);
//urlConnection.setConnectTimeout(15000);
//urlConnection.setReadTimeout(15000);
//urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
Log.i("Tag:", Integer.toString(responseCode)); //tag 200
//HttpPost httppost = new HttpPost("http://databasecall.php");
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//HttpResponse response = httpclient.execute(httppost);
//HttpEntity entity = response.getEntity();
//is = entity.getContent();
/*}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}*/
//convert response to string
//try{
//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.i("Tag:", result);
}
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
Updated API
try {
String urlParameters = "name=toni&class=one¶m3=ok";
byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
int postDataLength = postData.length;
String request = "http://rocks.php";
URL url = new URL(request);
HttpURLConnection cox = (HttpURLConnection) url.openConnection();
cox.setDoOutput(true);
cox.setDoInput(true);
cox.setInstanceFollowRedirects(false);
cox.setRequestMethod("POST");
cox.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
cox.setRequestProperty("charset", "utf-8");
cox.setRequestProperty("Content-Length",
Integer.toString(postDataLength));
cox.setUseCaches(false);
OutputStreamWriter writer = new OutputStreamWriter(
cox.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(
cox.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
} catch (Exception e) {
result = e.toString();
Sucess = false;
e.printStackTrace();
}