i want to give whole google drive access from my application to users.
and i use following code to authorize from google and oauth2.0.
function OpenGoogleLogin()
{
var url = "https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/drive&redirect_uri=http://localhost:8080/Abc/Oauth2callback&response_type=code&client_id=xxxxxxxxxxxxxxxxxxxxxxxxxx&access_type=offline&approval_prompt=force";
window.location = url;
}
from the above code i got authorization code.
on redirected page i put following servlet code
public class Oauth2callback extends HttpServlet {
private static final long serialVersionUID = 1L;
public Oauth2callback() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("entering doGet");
try {
// get code
String code = request.getParameter("code");
// format parameters to post
String urlParameters = "code="
+ code
+ "&client_id=xxxxxxxxxxxxxxxxxxxxx"
+ "&client_secret=xxxxxxxxxxxxxxxxxx"
+ "&redirect_uri=http://localhost:8080/Abc/Oauth2callback"
+ "&grant_type=authorization_code";
//post parameters
URL url = new URL("https://accounts.google.com/o/oauth2/token");
URLConnection urlConn = url.openConnection();
urlConn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(
urlConn.getOutputStream());
writer.write(urlParameters);
writer.flush();
//get output in outputString
String line, outputString = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(
urlConn.getInputStream()));
while ((line = reader.readLine()) != null) {
outputString += line;
}
System.out.println(outputString);
//get Access Token
JsonObject json = (JsonObject)new JsonParser().parse(outputString);
String access_token = json.get("access_token").getAsString();
System.out.println(access_token);
//get User Info
url = new URL(
"https://www.googleapis.com/oauth2/v1/userinfo?access_token="
+ access_token);
urlConn = url.openConnection();
outputString = "";
reader = new BufferedReader(new InputStreamReader(
urlConn.getInputStream()));
while ((line = reader.readLine()) != null) {
outputString += line;
}
System.out.println(outputString);
// Convert JSON response into Pojo class
GooglePojo data = new Gson().fromJson(outputString, GooglePojo.class);
System.out.println(data);
writer.close();
reader.close();
} catch (MalformedURLException e) {
System.out.println( e);
} catch (ProtocolException e) {
System.out.println( e);
} catch (IOException e) {
System.out.println( e);
}
System.out.println("leaving doGet");
}
}
in the above code , google pojo is just a pojo class, but i don't know when i run that servlet, it give me access and refrshtoken..
but with that it gives me error
java.io.IOException: Server returned HTTP response code: 403 for URL: https://www.googleapis.com/oauth2/v1/userinfo?access_token=xxxxxxxxxxxxx.
You are making the initial authorization request with scope https://www.googleapis.com/auth/drive, and using it's code to call https://www.googleapis.com/oauth2/v1/userinfo.
If you want to get user profile information, you will have to use one of these scopes in your initial request,
https://www.googleapis.com/auth/userinfo.email : View email address
https://www.googleapis.com/auth/userinfo.profile : View basic profile info
So, change your first url to
var url = "https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/userinfo.profile&redirect_uri=http://localhost:8080/Abc/Oauth2callback&response_type=code&client_id=xxxxxxxxxxxxxxxxxxxxxxxxxx&access_type=offline&approval_prompt=force";
You need to URLEncode the request parameters. A URL isn't valid as a parameter without encoding.
Related
I'm trying to connect jira server using java, I'm receiving "404 error".
I'm sharing the base url and code using which i'm trying to connect the jira server, please let me know what is wrong
public class Automate {
public static void main(String[] args) {
String baseURL = "https://thread.atlassian.net/";
String loginURL = "auth/1/session";
String loginUserName = "*********.com";
String loginPassword = "*******";
if (!errorOccurred) {
loginResponse = loginToJira(baseURL, loginURL, loginUserName, loginPassword);
if (loginResponse == "ERROR") {
errorOccurred = true;
}
}
public static String loginToJira(String baseURL, String loginURL, String loginUserName, String loginPassword) {
String loginResponse = "";
URL url = null;
HttpURLConnection conn = null;
String input = "";
OutputStream outputStream = null;
BufferedReader bufferedReader = null;
String output = null;
try {
//Create URL
url = new URL(baseURL + loginURL);
//Use URL to create connection
conn = (HttpURLConnection) url.openConnection();
//Set properties
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("content.type", "application/json");
//Create Json post object
input = "{\"Username\" :\"" + loginUserName + "\" \"Password\" :\"" + loginPassword + "\"}";
//Send our request
outputStream = conn.getOutputStream();
//System.out.println("outputStream:"+outputStream);
outputStream.write(input.getBytes());
//System.out.println("outputStream after writing input:"+outputStream);
outputStream.flush();
//System.out.println("outputStream after Flushing:"+outputStream);
//Handle our response
System.out.println("Get Response :"+ conn.getResponseCode() );
if (conn.getResponseCode() == 200) {
bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
System.out.println("Connection Stream:"+bufferedReader);
while ((output = bufferedReader.readLine()) != null) {
loginResponse += output;
}
conn.disconnect();
}
} catch (Exception ex) {
//Handle errors
System.out.println("Error in login Jira" + ex.getMessage());
return loginResponse = "ERROR";
}
System.out.println("\nloginResponse:");
System.out.println(loginResponse);
return loginResponse;
}
}
Please check the URL again. The page does not exist even when accessed from a browser. Try using just base URL as it redirects to login or a different login URL.
I am having service throwing RuntimeException which working fine with ajax Call. If i call that service using HttpUrlConnection from another java program exception string not getting instead its showing 'Internal Server Error' with response code 500.
#Path("poService")
public class PoService {
#Context
private UriInfo context;
#GET
#Path("getPo/{poNo}")
#Produces(MediaType.APPLICATION_JSON)
public Response getPo(#PathParam("poNo") int poNo ) throws Exception{
String urlStr = AppConstant.WEBOLIS_PATH + "po.htm?getPoForSrnConsReport=true&pono="+poNo ;
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//con.setRequestProperty("User-Agent", AppConstant.USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
System.out.println("Response Code : " + con.getResponseMessage());
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
if( responseCode!=200 ){ // if any Error
//throw new WebolisApiException( responseCode, response.toString());
}else{
}
return Response.ok( response.toString(), MediaType.APPLICATION_JSON).build();
}
}
This is above REST method from which I am calling to another java Spring Controller.
#RequestMapping( value="/po", method=RequestMethod.GET,params= {"getPoForSrnConsReport"}) //,consumes="application/json"
#ResponseBody ModelMap getPoForSrnConsReport(HttpServletResponse response,
#RequestParam(value = "pono" ) Integer poNo) throws Exception {
ModelMap m = new ModelMap();
PoService poService = new PoService();
Po po = poService.getPo(poNo, poService.ALL_ITEMS , Boolean.FALSE);
m.addAttribute("po",po);
return m;
}
in PoService i am throwing Custom Exception 'PO not Found' This string is not available in REST method
Trying to open a connection to a server that sends an error code will throw an exception, that you need to catch. Also you cannot use getInputStream() when you get an error response code. You need to use getErrorStream():
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
}
catch(IOException e) {
// handle specific exceptions here
}
int responseCode = -1;
try {
responseCode = con.getResponseCode();
}
catch(IOException e) {
// handle specific exceptions here
}
// override the input if you got an error and an error stream is available
if (in==null && responseCode!=200 && con.getErrorStream() != null) {
in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
}
I have a class that has two methods that have a lot of duplicate code but the bit that's unique is in the middle of the whole thing. From my research I think I should be doing the "Execute around method" pattern but I can't find a resource that I can follow as they all seem to use code I can't replicate.
I have two methods, apiPost and apiGet, which I've pasted below. I've wrapped the unique parts of these methods with comments showing where the unique section starts and ends:
/**
* Class that handles authorising the connection and handles posting and getting data
*
* #version %I%, %G%
* #since 1.0
*/
public class CallHandler {
private static PropertyLoader props = PropertyLoader.getInstance();
final static int MAX = props.getPropertyAsInteger(props.MAX_REQUESTS);
private final Logger log = LoggerFactory.getLogger(CallHandler.class);
private final static String POST = "POST";
private final static String GET = "GET";
/**
* Makes a POST call to the API URL provided and returns the JSON response as a string
* http://stackoverflow.com/questions/15570656/how-to-send-request-payload-to-rest-api-in-java
*
* #param urlString the API URL to send the data to, as a string
* #param payload the serialised JSON payload string
* #return and value returned as a JSON string, ready to be deserialised
*/
public String apiPost(String urlString, String payload) {
boolean keepGoing = true;
int tries = 0;
String line;
StringBuilder jsonString = new StringBuilder();
log.debug("Making API Call: {}", urlString);
while (keepGoing && tries < MAX) {
tries++;
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// UNIQUE CODE START
prepareConnection(connection, POST);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
// UNIQUE CODE END
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
keepGoing = false;
} catch (Exception e) {
log.warn("Try #{}. Error posting: {}", tries, e.getMessage());
log.warn("Pausing for 1 second then trying again...");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException f) {
log.warn("Sleeping has been interrupted: {}", f.getMessage());
}
}
}
return jsonString.toString();
}
/**
* Makes a GET call to the API URL provided and returns the JSON response as a string
* http://stackoverflow.com/questions/2793150/using-java-net-urlconnection-to-fire-and-handle-http-requests
*
* #param urlString the API URL to request the data from, as a string
* #return the json response as a string, ready to be deserialised
*/
public String apiGet(String urlString) {
boolean keepGoing = true;
int tries = 0;
String line;
StringBuilder jsonString = new StringBuilder();
log.debug("Making API Call: {}", urlString);
while (keepGoing && tries < MAX) {
tries++;
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// UNIQUE CODE START
prepareConnection(connection, GET);
connection.connect();
// UNIQUE CODE END
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
keepGoing = false;
} catch (Exception e) {
log.warn("Try #{}. Error getting from API: {}", tries, e.getMessage());
log.warn("Pausing for 1 second then trying again...");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException f) {
log.warn("Sleeping has been interrupted: {}", f.getMessage());
}
}
}
return jsonString.toString();
}
/**
* Prepares the HTTP Url connection depending on whether this is a POST or GET call
*
* #param connection the connection to prepare
* #param method whether the call is a POST or GET call
*/
private void prepareConnection(HttpURLConnection connection, String method) {
String charset = "UTF-8";
try {
connection.setRequestMethod(method);
if (method.equals(GET)) {
connection.setRequestProperty("Accept-Charset", charset);
} else if (method.equals(POST)) {
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json; charset=" + charset);
}
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", "Bearer " + apiKey);
} catch (Exception e) {
log.error("Error preparing HTTP URL connection: {}", e.getMessage());
throw new RuntimeException(e.getMessage());
}
}
Can I use the "Execute around method" pattern to save on code duplication here? If so could someone help me figure out how to refactor this code to make use of it. If this is the wrong way to go about it could someone suggest a smart alternative?
It can be done by extracting "unique" code into special worker. More specifically for example, you can use lambda expressions:
public String apiPost(String urlString, String payload) {
return commonMethod(urlString, payload, (connection) -> {
// UNIQUE CODE START
prepareConnection(connection, POST);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
// UNIQUE CODE END
});
}
interface ConnectionWorker {
void run(HttpURLConnection connection) throws IOException;
}
public String commonMethod(String urlString, String payload, ConnectionWorker worker) {
boolean keepGoing = true;
int tries = 0;
String line;
StringBuilder jsonString = new StringBuilder();
log.debug("Making API Call: {}", urlString);
while (keepGoing && tries < MAX) {
tries++;
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
worker.run(connection);
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
keepGoing = false;
} catch (Exception e) {
log.warn("Try #{}. Error posting: {}", tries, e.getMessage());
log.warn("Pausing for 1 second then trying again...");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException f) {
log.warn("Sleeping has been interrupted: {}", f.getMessage());
}
}
}
return jsonString.toString();
}
UPDATE: In case if you can not use java 8 and lambda, you can always switch to creating anonymous class:
return commonMethod(urlString, payload, new ConnectionWorker() {
#Override
public void run(HttpURLConnection connection) throws IOException {
// UNIQUE CODE START
CallHandler.this.prepareConnection(connection, POST);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
// UNIQUE CODE END
}
});
I am trying to implement facebook login in my java application. Till now on button click i have called the servlet where it according to client id and secret key generate code and redirect it to the redirect uri. I have registered my test app on facebook developer console.
Problem is that code is generating perfectly but access token is not getting generated through which I will get the basic Info. I have tried many codes. One of them is below.
CLIENT SIDE
google.addClickHandler(new ClickHandler()
{
#Override
public void onClick(ClickEvent event) {
String fbURL = "http://www.facebook.com/dialog/oauth?client_id=CLIENTID&redirect_uri=REDIRECT URL &scope=email&scope=user_friends";
Window.open(fbURL,"_blank","");
}
});
SERVLET
public userInfoServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
PrintWriter out = response.getWriter();
String rid = request.getParameter("request_ids");
if (rid != null) {
response.sendRedirect("https://www.facebook.com/dialog/oauth?client_id="
+ clientID + "&redirect_uri=" + redirectURI);
} else {
// Get code
String code = request.getParameter("code");
if (code != null) {
// Format parameters
URL url = new URL(
"https://graph.facebook.com/oauth/access_token?client_id="
+ clientID + "&redirect_uri=" + redirectURI
+ "&client_secret=" + clientSecret
+ "&code=" + code);
// request for Access Token
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");
String line, outputString = "";
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
outputString += line;
}
out.println(outputString);
// extract access token from response
String accessToken = null;
if(outputString.indexOf("access_token")!=-1) {
accessToken = outputString.substring(13,outputString.indexOf("&"));
}
// request for user info
url = new URL("https://graph.facebook.com/me?access_token="
+ accessToken);
out.println(url);
URLConnection conn1 = url.openConnection();
outputString = "";
reader = new BufferedReader(new InputStreamReader(
conn1.getInputStream()));
while ((line = reader.readLine()) != null) {
outputString += line;
}
reader.close();
out.println(outputString);
// convert response JSON to Pojo class
FaceBookPojo fbp = new Gson().fromJson(outputString,
FaceBookPojo.class);
out.println(fbp);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
I am not getting what exactly the problem in generating the access token. Any help would be appreciable.
tried this code also but the problem is same
there is multiple scope parameters in your req. It should be only one.
Try this,
google.addClickHandler(new ClickHandler()
{
#Override
public void onClick(ClickEvent event) {
String fbURL = "http://www.facebook.com/dialog/oauth?client_id=CLIENTID&redirect_uri=REDIRECT URL &scope=email,user_friends";
Window.open(fbURL,"_blank","");
}
});
It should works.
import java.net.*;
import java.io.*;
public class sample
{
public static void main (String args[])
{
String line;
try
{
URL url = new URL( "http://localhost:8080/WeighPro/CommPortSample" );
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
line = in.readLine();
System.out.println( line );
in.close();
}
catch (Exception e)
{
System.out.println("Hello Project::"+e.getMessage());
}
}
}
My Servlet is invoking another Jsp page like the below,
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
I am not getting any reaction/output in the browser, where the servlet has to be executed once it is invoked.
Am I missing any basic step for this process? Please Help!!!
If you want to open it in browser try this
java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://localhost:8080/WeighPro/CommPortSample"));
You question is not clear. Do you actually want to invoke a Servlet from the Main method, or do you want to make an HTTP request to your web application?
If you want to make an HTTP request, I can't see any obvious problems with your code above, which makes me believe that the problem is in the Servlet. You also mention that you don't get anything in the browser, but running your program above does not involve a browser.
Do you mean that you don't get a response when you go to
http://localhost:8080/WeighPro/CommPortSample
in a browser?
As Suresh says, you cannot call a Servlet directly from a main method.
Your Servlet should instead call methods on other classes, and those other classes should be callable from the main method, or from Test Cases. You need to architect your application to make that possible.
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class OutBoundSimul {
public static void main(String[] args) {
sendReq();
}
public static void sendReq() {
String urlString = "http://ip:port/applicationname/servletname";
String respXml = text;
URL url = null;
HttpURLConnection urlConnection = null;
OutputStreamWriter out = null;
BufferedInputStream inputStream = null;
try {
System.out.println("URL:"+urlString);
url = new URL(urlString);
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
System.out.println("SendindData");
out = new OutputStreamWriter(urlConnection.getOutputStream());
System.out.println("Out:"+out);
out.write(respXml);
out.flush();
inputStream = new BufferedInputStream(urlConnection.getInputStream());
int character = -1;
StringBuffer sb = new StringBuffer();
while ((character = inputStream.read()) != -1) {
sb.append((char) character);
}
System.out.println("Resp:"+sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Invoking Servlet with query parameters Form Main method
Java IO
public static String accessResource_JAVA_IO(String httpMethod, String targetURL, String urlParameters) {
HttpURLConnection con = null;
BufferedReader responseStream = null;
try {
if (httpMethod.equalsIgnoreCase("GET")) {
URL url = new URL( targetURL+"?"+urlParameters );
responseStream = new BufferedReader(new InputStreamReader( url.openStream() ));
}else if (httpMethod.equalsIgnoreCase("POST")) {
con = (HttpURLConnection) new URL(targetURL).openConnection();
// inform the connection that we will send output and accept input
con.setDoInput(true); con.setDoOutput(true); con.setRequestMethod("POST");
con.setUseCaches(false); // Don't use a cached version of URL connection.
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
con.setRequestProperty("Content-Language", "en-US");
DataOutputStream requestStream = new DataOutputStream ( con.getOutputStream() );
requestStream.writeBytes(urlParameters);
requestStream.close();
responseStream = new BufferedReader(new InputStreamReader( con.getInputStream(), "UTF-8" ));
}
StringBuilder response = new StringBuilder(); // or StringBuffer if not Java 5+
String line;
while((line = responseStream.readLine()) != null) {
response.append(line).append('\r');
}
responseStream.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace(); return null;
} finally {
if(con != null) con.disconnect();
}
}
Apache Commons using commons-~.jar
{httpclient, logging}
public static String accessResource_Appache_commons(String url){
String response_String = null;
HttpClient client = new HttpClient();
GetMethod method = new GetMethod( url );
// PostMethod method = new PostMethod( url );
method.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
method.setQueryString(new NameValuePair[] {
new NameValuePair("param1","value1"),
new NameValuePair("param2","value2")
}); //The pairs are encoded as UTF-8 characters.
try{
int statusCode = client.executeMethod(method);
System.out.println("Status Code = "+statusCode);
//Get data as a String OR BYTE array method.getResponseBody()
response_String = method.getResponseBodyAsString();
method.releaseConnection();
} catch(IOException e) {
e.printStackTrace();
}
return response_String;
}
Apache using httpclient.jar
public static String accessResource_Appache(String url) throws ClientProtocolException, IOException{
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
URIBuilder builder = new URIBuilder( url )
.addParameter("param1", "appache1")
.addParameter("param2", "appache2");
HttpGet method = new HttpGet( builder.build() );
// HttpPost method = new HttpPost( builder.build() );
// Create a custom response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
#Override
public String handleResponse( final HttpResponse response) throws IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
}
return "";
}
};
return httpclient.execute( method, responseHandler );
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
JERSY using JARS {client, core, server}
public static String accessResource_JERSY( String url ){
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource( url );
ClientResponse response = service.accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);
if (response.getStatus() != 200) {
System.out.println("GET request failed >> "+ response.getStatus());
}else{
String str = response.getEntity(String.class);
if(str != null && !str.equalsIgnoreCase("null") && !"".equals(str)){
return str;
}
}
return "";
}
Java Main method
public static void main(String[] args) throws IOException {
String targetURL = "http://localhost:8080/ServletApplication/sample";
String urlParameters = "param1=value11¶m2=value12";
String response = "";
// java.awt.Desktop.getDesktop().browse(java.net.URI.create( targetURL+"?"+urlParameters ));
// response = accessResource_JAVA_IO( "POST", targetURL, urlParameters );
// response = accessResource_Appache_commons( targetURL );
// response = accessResource_Appache( targetURL );
response = accessResource_JERSY( targetURL+"?"+urlParameters );
System.out.println("Response:"+response);
}
Simply you cannot do that.
A response and request pair will generated by web container. You cannot generate a response object and send to the browser.
By the way which client/browser you are expecting to get the response ? No idea. Right ?
When container receives a request from client then it generates response object and serves you can access that response in service method.
If you want to see/test the response, you have to request from there.