To write the response of servlet into pdf using httpurlconnection - java

I am trying to hit a url through URL Connection in servlet. The response of the request (which is a pdf) needs to be displayed on the browser as pdf. Here I do not have any temporary pdf file kept on the server which means i want my code to generate the url response as a pdf on the fly. Currently my webservice returns pdf if I hit the webservice url(REST) directly in the browser.
Here is my code
I am getting a blank output
code:
package com.mm;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class testServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\""+ "dummy" + "\"");
byte[] pdfData = servicecall().getBytes("UTF-8");
System.out.println(pdfData.length);
response.setContentLength(pdfData.length);
OutputStream output = response.getOutputStream();
output.write(pdfData);
output.flush();
output.close();
}
public String servicecall()
{
String output = "";
BufferedReader reader = null;
StringBuilder stringBuilder;
try
{
URL url = new URL("http://hardik/Wecs/External/private/document.aspx?prd=1042737~~PDF~~MTR~~IPDS~~EN~~2014-01-10%2014:00:41~~SOLEST%20120~~");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/pdf");
conn.connect();
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
reader = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
output = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println( output);
return output;
}
}
I get a blank pdf output

Related

How to perform post request in header and body in JSON

I'm using JSON and want to send post request to server via username, password in body and x-auth-app-id, x-auth-app-hash in header..
I have test on Postmen and it return 200 (status ok), But when I build my sources it happen error.
This is my class header:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import net.sf.json.JSONObject;
public class HttpRequestUtil {
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
InputStream inputStream=null;
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestProperty("x-auth-app-id", "6166611659356156223");
httpUrlConn.setRequestProperty("x-auth-app-hash", "a44f4ea21475fa6761392ba4bc659990bee771c413b2c207490a79f9ec78c2a61234");
httpUrlConn.setRequestProperty("Content-Type", "application/json");
httpUrlConn.setRequestMethod(requestMethod);
if ("POST".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
}
catch (ConnectException ce) {
ce.printStackTrace();
System.out.println("Our server connection timed out");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("https request error:{}");
}
finally {
try {
if(inputStream!=null) {
inputStream.close();
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jsonObject;
}
}
And class Body:
import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
public class CallCenterController {
public static void main(String[] args) throws JSONException {
String sipUser = "vchi_dd";
String sipPassword = "m9Bp7s+CtQj85HygnIFjPn7O4Vithrunaa";
Map<String, Object> sipAccount = new HashMap<String, Object>();
sipAccount.put("sipUser", sipUser);
sipAccount.put("sipPassword", sipPassword);
sipAccount = postData(sipUser, sipPassword);
System.out.println("result: " + sipAccount);
};
public static JSONObject postData(String sipUser, String sipPassword) {
String url="https://myservice.com/oapi/v1/call/click-to-call/02437590555&sipUser="+sipUser+"&sipPassword="+sipPassword;
return HttpRequestUtil.httpRequest(url, "POST", "");
}
}
When I build it happen an exception following as:
java.io.IOException: Server returned HTTP response code: 400 for URL: https://myservice.com/oapi/v1/call/click-to-call/02437590555&sipUser=vchi_dd&sipPassword=m9Bp7s+CtQj85HygnIFjPn7O4Vithrunaa
https request error:{}
result: null
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at com.mypackage.HttpRequestUtil.httpRequest(HttpRequestUtil.java:63)
at com.mypackage.CallCenterController.postData(CallCenterController.java:45)
at com.mypackage.CallCenterController.main(CallCenterController.java:34)
How to send correct data to my url and fix the problem?
I would use Java HTTP Client API if your java version is high enough.
Here's a link to it https://www.baeldung.com/java-9-http-client
I have used it and it feels more maintainable and clear.
Also, it seems that you're sending the request with empty body even though you say in your question that you are sending username and password in body.
And why are you adding username and password to a map if you are not using the map?
sipAccount.put("sipUser", sipUser);
sipAccount.put("sipPassword", sipPassword);

JSON post encoding in Elasticsearch through maven

I want to make insert in java.Maven with http post to Elasticsearch server.
My code is:
package com.server.java.Webping;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class ReadAndWrite extends Server {
public static void main(String[] args) throws IOException {
try {
URL url = new URL("http://192.168.1.126:9200/shakespeare/_bulk?pretty' --data-binary #shakespeare.json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
File file = new File("shakespeare.json");
FileReader reader = new FileReader(file);
#SuppressWarnings("resource")
BufferedReader br = new BufferedReader(reader);
String input = null;
StringBuilder builder = new StringBuilder();
while(br.readLine( ) != null)
{
String txt = br.readLine( );
builder.append(txt);
}
input = builder.toString();
OutputStream os = (OutputStream) conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br1 = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br1.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
However when I execute the post method, java return me an error:
java.io.IOException: Error writing to server
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:699)
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:711)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1567)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at com.server.java.Webping.ReadAndWrite.main(ReadAndWrite.java:38)
I have also checked my server connection with pinging socket request and its working .
code for pinging request:
package com.server.java.Webping;
import java.net.InetAddress;
import java.net.Socket;
public class WebPing {
public static void main(String[] args) {
try {
InetAddress addr;
Socket sock = new Socket("192.168.1.126", 9200); // elastic search - 9200 , kibana - 5601
addr = sock.getInetAddress();
System.out.println("Connected to " + addr);
sock.close();
} catch (java.io.IOException e) {
System.out.println("Can't connect to " + args[0]);
System.out.println(e);
}
}
}
and output returns as :
Connected to /192.168.1.126
Can anyone help me out that what is wrong in my code ?

HttpURLConnection returns 400, but request body is correct

I'm trying to connect a java application to the json api of betaface.
I ran into a weird problem I hope you guys can help me with.
I have the (ugly) code to connect to the api. This code is just to test what kind of responses I get and what to do with it.
I build a request body, print the request body to the console, and then write the request body to the api. The problem is that the responsecode is 400.
The weird thing is, when I copy the request body and execute it through Advanced Rest Client it will return a 200 and the expected body. I think the problem is not in the body but somewhere in the HTTPUrlConnection.
I've added my test class to illustrate the problem, you guys would only need a small image to reproduce the problem. The API keys are the free to use api keys of betaface.
Thank you very much for any help you can give me.
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import javax.imageio.ImageIO;
public class APITest {
/**
* #param args
*/
public static void main(String[] args) {
try
{
new APITest();
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public APITest() throws MalformedURLException, IOException {
String api_key = "d45fd466-51e2-4701-8da8-04351c872236";
String api_secret = "171e8465-f548-401d-b63b-caf0dc28df5f";
String urlToConnect = "http://www.betafaceapi.com/service_json.svc/UploadNewImage_File";
File fileToUpload = new File("C:\\test.jpg");
byte[] t = getImageBase64ByteArray(fileToUpload);
String body = "";
body += "{\"api_key\":\"";
body += api_key;
body += "\",\"api_secret\":\"";
body += api_secret;
body += "\",\"detection_flags\":\"\",\"imagefile_data\":[";
for(int i = 0; i < t.length; i++) {
body += t[i];
if(i < t.length - 1)
body += ",";
}
body += "],\"original_filename\":\"Test.jpg\"}";
System.out.println(body);
HttpURLConnection connection = (HttpURLConnection)new URL(urlToConnect).openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
BufferedWriter writer =
new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
writer.write(body);
writer.newLine();
writer.flush();
writer.close();
int responseCode = connection.getResponseCode();
System.out.println(responseCode); // Should be 200
InputStream errorstream = connection.getErrorStream();
BufferedReader br = null;
if (errorstream == null){
InputStream inputstream = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(inputstream));
}else{
br = new BufferedReader(new InputStreamReader(errorstream));
}
String response = "";
String line;
while ((line = br.readLine()) != null){
response += line;
}
System.out.println(response);
}
public byte[] getImageBase64ByteArray(File file) {
BufferedImage bufferedImage;
try
{
bufferedImage = ImageIO.read(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String encoded = "";
try {
ImageIO.write(bufferedImage, "jpg", bos);
byte[] imageBytes = bos.toByteArray();
encoded = Base64.getEncoder().encodeToString(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return encoded.getBytes();
}
catch(IOException e)
{
e.printStackTrace();
}
return new byte[0];
}
}

FileNotFoundException while parsing json in android 4.0.4 but works in android 2.3.3

I am trying to access the json that displays the contents of my android application. The FileNotFound exception is throwing in Android 4.0.4 but the json can be accessed in Android 2.3.3. The json can also be accessed from browser using the same url. What is wrong in the code ? Can anyone help me regarding this issue.
I am using the code below:
url = new URL("http://www.dynamiskdesign.se/ipromotionnew/json/148.json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
InputStream input = httpURLConnection.getInputStream();
if (input != null) {
writer = new StringWriter();
char[] buffer = new char[1024];
Reader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
input.close();
}
String jsontext = writer.toString();
This is because the combination of network and threads.
Explanation is also on that page (link).
I had this too, look at this answer:
httpclient (phpmyadmin) not working on Android 4.0+
I think this solution can work:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
//
public class Connector extends AsyncTask<TextView, Void, String> {
#Override
protected String doInBackground(TextView... params) {
// TODO Auto-generated method stub
return GetSomething();
}
private final String getSomething() {
try{
url=new URL("http://www.dynamiskdesign.se/ipromotionnew/json/148.json");
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
InputStream input=httpURLConnection.getInputStream();
} catch(Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
//convert response to string
try{
if (input != null)
{
writer = new StringWriter();
char[] buffer = new char[1024];
Reader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
input.close();
}
} catch(Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
String jsontext = writer.toString();
} catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
protected void onPostExecute(String page) {
//onPostExecute
}
}

Checking Content-Type of HTTP POST Request to Java servlet

I've written a simple servlet that accepts HTTP POST requests and sends back a short response. Here's the code for the servlet:
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.*;
/**
* Servlet implementation class MapleTAServlet
*/
#WebServlet(description = "Receives XML request text containing grade data and returns response in XML", urlPatterns = { "/MapleTAServlet" })
public class MapleTAServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Log log = LogFactory.getLog(MapleTAServlet.class);
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String strXMLResponse = "<Response><code>";
String strMessage = "";
int intCode = 0;
ServletOutputStream stream = null;
BufferedInputStream buffer = null;
try
{
String strContentType = request.getContentType();
// Make sure that the incoming request is XML data, otherwise throw up a red flag
if (strContentType != "text/xml")
{
strMessage = "Incorrect MIME type";
}
else
{
intCode = 1;
} // end if
strXMLResponse += intCode + "</code><message>" + strMessage + "</message></Response>";
response.setContentType("text/xml");
response.setContentLength(strXMLResponse.length());
int intReadBytes = 0;
stream = response.getOutputStream();
// Converts the XML string to an input stream of a byte array
ByteArrayInputStream bs = new ByteArrayInputStream(strXMLResponse.getBytes());
buffer = new BufferedInputStream(bs);
while ((intReadBytes = buffer.read()) != -1)
{
stream.write(intReadBytes);
} // end while
}
catch (IOException e)
{
log.error(e.getMessage());
}
catch (Exception e)
{
log.error(e.getMessage());
}
finally
{
stream.close();
buffer.close();
} // end try-catch
}
}
And here's the client that I'm using to send the request:
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.*;
public class TestClient
{
/**
* #param args
*/
public static void main(String[] args)
{
BufferedReader inStream = null;
try
{
// Connect to servlet
URL url = new URL("http://localhost/mapleta/mtaservlet");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Initialize the connection
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "text/xml");
//conn.setRequestProperty("Connection", "Keep-Alive");
conn.connect();
OutputStream out = conn.getOutputStream();
inStream = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String strXMLRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Request></Request>";
out.write(strXMLRequest.getBytes());
out.flush();
out.close();
String strServerResponse = "";
System.out.println("Server says: ");
while ((strServerResponse = inStream.readLine()) != null)
{
System.out.println(strServerResponse);
} // end while
inStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
} // end try catch
}
}
The issue I'm having is that when I run the client program, I'm getting the following output:
Server says:
<Response><code>0</code><message>Incorrect MIME type</message></Response>
I've tried calling request.getContentType() and have gotten "text/xml" as the output. Just trying to figure out why the string isn't matching up.
You're comparing strings the wrong way.
if (strContentType != "text/xml")
Strings are not primitives, they are objects. When using != to compare two objects, it will only test if they do not point to the same reference. However, you're rather interested in comparing the content of two different string references, not if they point to the same reference.
You should then use the equals() method for this:
if (!strContentType.equals("text/xml"))
Or, better, to avoid NullPointerException if the Content-Type header is not present (and thus becomes null):
if (!"text/xml".equals(strContentType))

Categories