Implementation steps;First Create URL object and create HttpURLConnection by using above object.openConnection();Then create BufferedInputStream by passing InputStream to constructer of BufferedInputStream.Finally writes this buffered input stream data to output stream of the servlet.
package com.srccodes.example;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class OldBillClient extends HttpServlet {
private static final long serialVersionUID = 1L;
public OldBillClient() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
//System.out.println("Done");
}
HttpURLConnection conn;
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doDL();//Create URL connection for download and show
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());//Used created connection
OutputStream sos = response.getOutputStream();
try {
int i = 0;
while ((i = in.read()) != -1) {
sos.write(i);//Writes data to out put stream
//System.out.write(i);
}
in.close();
sos.flush();
} finally {
if (in != null)
in.close();
if (sos != null) {
sos.flush();
sos.close();
}
}
}
/**
* set URL connection
*/
private void doDL() {
try {
URL obj = new URL("https://www.google.lk/#q=Test");//Ex : http://170.26.29.180/com/test/?para_1=value_1¶_2=value_2
conn = (HttpURLConnection) obj.openConnection();
conn.setReadTimeout(5000);
} catch (java.io.IOException ioE) {
ioE.getMessage();
} catch (Exception e) {
e.printStackTrace();
}
}
}
No comments:
Post a Comment