This question already has an answer here:
RestTemplate vs Apache Http Client for production code in spring project
(1 answer)
Closed 4 years ago.
Should I use HttpURLConnection in a Spring Project Or better to use RestTemplate ?
In other words, When it is better to use each ?
The HttpURLConnection and RestTemplate are different kind of beasts. They operate on different abstraction levels.
The RestTemplate helps to consume REST api and the HttpURLConnection works with HTTP protocol.
You're asking what is better to use. The answer depends on what you're trying to achieve:
If you need to consume REST api then stick with RestTemplate
If you need to work with http protocol then use HttpURLConnection, OkHttpClient, Apache's HttpClient, or if you're using Java 11 you can try its HttpClient.
Moreover the RestTemplate uses HttpUrlConnection/OkHttpClient/... to do its work (see ClientHttpRequestFactory, SimpleClientHttpRequestFactory, OkHttp3ClientHttpRequestFactory
Why you should not use HttpURLConnection?
It's better to show some code:
In examples below JSONPlaceholder used
Let's GET a post:
public static void main(String[] args) {
URL url;
try {
url = new URL("https://jsonplaceholder.typicode.com/posts/1");
} catch (MalformedURLException e) {
// Deal with it.
throw new RuntimeException(e);
}
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
try (InputStream inputStream = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(isr)) {
// Wrap, wrap, wrap
StringBuilder response = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
// Here is the response body
System.out.println(response.toString());
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
Now let's POST a post something:
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "application/json; charset=UTF-8");
try (OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter wr = new BufferedWriter(osw)) {
wr.write("{\"title\":\"foo\", \"body\": \"bar\", \"userId\": 1}");
}
If the response needed:
try (InputStream inputStream = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(isr)) {
// Wrap, wrap, wrap
StringBuilder response = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
System.out.println(response.toString());
}
As you can see the api provided by the HttpURLConnection is ascetic.
You always have to deal with "low-level" InputStream, Reader, OutputStream, Writer, but fortunately there are alternatives.
The OkHttpClient
The OkHttpClient reduces the pain:
GETting a post:
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("https://jsonplaceholder.typicode.com/posts/1")
.build();
Call call = okHttpClient.newCall(request);
try (Response response = call.execute();
ResponseBody body = response.body()) {
String string = body.string();
System.out.println(string);
} catch (IOException e) {
throw new RuntimeException(e);
}
POSTing a post:
Request request = new Request.Builder()
.post(RequestBody.create(MediaType.parse("application/json; charset=UTF-8"),
"{\"title\":\"foo\", \"body\": \"bar\", \"userId\": 1}"))
.url("https://jsonplaceholder.typicode.com/posts")
.build();
Call call = okHttpClient.newCall(request);
try (Response response = call.execute();
ResponseBody body = response.body()) {
String string = body.string();
System.out.println(string);
} catch (IOException e) {
throw new RuntimeException(e);
}
Much easier, right?
Java 11's HttpClient
GETting the posts:
HttpClient httpClient = HttpClient.newHttpClient();
HttpResponse<String> response = httpClient.send(HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.GET()
.build(), HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
POSTing a post:
HttpResponse<String> response = httpClient.send(HttpRequest.newBuilder()
.header("Content-Type", "application/json; charset=UTF-8")
.uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
.POST(HttpRequest.BodyPublishers.ofString("{\"title\":\"foo\", \"body\": \"barzz\", \"userId\": 2}"))
.build(), HttpResponse.BodyHandlers.ofString());
The RestTemplate
According to its javadoc:
Synchronous client to perform HTTP requests, exposing a simple, template method API over underlying HTTP client libraries such as the JDK {#code HttpURLConnection}, Apache HttpComponents, and others.
Lets do the same
Firstly for convenience the Post class is created. (When the RestTemplate will read the response it will transform it to a Post using HttpMessageConverter)
public static class Post {
public long userId;
public long id;
public String title;
public String body;
#Override
public String toString() {
return new ReflectionToStringBuilder(this)
.toString();
}
}
GETting a post.
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Post> entity = restTemplate.getForEntity("https://jsonplaceholder.typicode.com/posts/1", Post.class);
Post post = entity.getBody();
System.out.println(post);
POSTing a post:
public static class PostRequest {
public String body;
public String title;
public long userId;
}
public static class CreatedPost {
public String body;
public String title;
public long userId;
public long id;
#Override
public String toString() {
return new ReflectionToStringBuilder(this)
.toString();
}
}
public static void main(String[] args) {
PostRequest postRequest = new PostRequest();
postRequest.body = "bar";
postRequest.title = "foo";
postRequest.userId = 11;
RestTemplate restTemplate = new RestTemplate();
CreatedPost createdPost = restTemplate.postForObject("https://jsonplaceholder.typicode.com/posts/", postRequest, CreatedPost.class);
System.out.println(createdPost);
}
So to answer your question:
When it is better to use each ?
Need to consume REST api? Use RestTemplate
Need to work with http? Use some HttpClient.
Also worth mentioning:
Retrofit
Intro to Feign
Declarative REST client
Related
I am currently learning to consume an API in Java, I am using the Exchange Rates API, however, it failed to understand what is happening, I send all the requested parameters and I also send my API key as header.
private static void sendHttpGETRequest(String fromCode, String toCode, double amount) throws IOException, JSONException{
String GET_URL = "https://api.apilayer.com/exchangerates_data/convert?to="+toCode+"&from="+fromCode+"&amount="+amount;
URL url = new URL(GET_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(200 * 1000);
httpURLConnection.setConnectTimeout(200 * 1000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("apikey", "MyApiKeY");
int responseCode = httpURLConnection.getResponseCode();
System.out.println("Response code: " + responseCode);
if(responseCode == httpURLConnection.HTTP_OK){//SUCESS
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while((inputLine = in.readLine()) != null){
response.append(inputLine);
}in.close();
JSONObject obj = new JSONObject(response.toString());
Double exchangeRate = obj.getJSONObject("rates").getDouble(fromCode);
System.out.println(obj.getJSONObject("rates"));
System.out.println(exchangeRate); //keep for debugging
System.out.println();
}
else {
System.out.println("GET request failed");
}
}
I have used setConnectTimeout and setReadTimeout to set the network timeout thinking that was the problem but still getting the same error.
I ran into a similar issue while using Spring Web's RestTemplate to try and make the API call.
APILayer is using OKHttpClient (from the okhttp3 library) for their demo samples.
This fixed it for me.
Here is what this could look like for you:
import java.io.*;
import okhttp3.*;
public class main {
public static void main(String []args) throws IOException{
OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder()
.url("https://api.apilayer.com/exchangerates_data/convert?to=to&from=from&amount=amount")
.addHeader("apikey", "MyApiKeY")
.method("GET", })
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
}
}
Here is my code
private static final String MEDIA_TYPE = "application/json";
private static final String FORMAT = "UTF-8";
private static String baseServiceUrl;
private static String apiServiceUrl;
#RequestMapping("/")
public ResponseEntity<?> getMessage() throws Exception {
logger.info("Started");
try {
messageProcessor.getMessage("test service");
// Read from request
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString();
StringRequestEntity requestEntity = null;
HttpClient httpclient = new HttpClient();
int statusCode;
logger.info("RequestBody"+data);
baseServiceUrl="http://localhost:8080/services";
apiServiceUrl="/services/rest/json";
StringBuffer eventResponse = new StringBuffer();
requestEntity = new StringRequestEntity(data, MEDIA_TYPE, FORMAT);
PostMethod postMethod = new PostMethod(baseServiceUrl+apiServiceUrl);
postMethod.setRequestEntity(requestEntity);
statusCode = httpclient.executeMethod(postMethod);
logger.info("Status code"+statusCode);
}
catch (Exception ex) {
logger.error("Exception occurs ", ex);
return new ResponseEntity("Internal server error !!", HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity("Successfully called the service!!", HttpStatus.OK);
}
I want to get the requestbody of one API and send to another API .And a json is my request body.But in this code,I got the status code as 400.Can anyone help me to solve the problem
I think you have appended the /services in the url twice. It should be like:
baseServiceUrl="http://localhost:8080/services";
apiServiceUrl="/rest/json";
In your code you are reading the request body as a string , could you share the request body that is logged.The HTTP response code 400 corresponds to BAD request . So probably, either the endpoint that you are trying to hit is different or the request body has an issue. Try removing the /services from your apiServiceUrl to correct the url path.Also, since you are most probably having a json as request body try the following approach :
String json = "{"id":1,"name":"xxxx"}";
StringEntity entity = new StringEntity(json);
postMethod.setEntity(entity);
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
make sure that the string that you read from the request using BufferedReader reader = request.getReader(); is in appropriate json format.
I have developed a web service in Java. Below is a method of it.
#Path("/setup")
public class SetupJSONService {
#POST
#Path("/insertSetup")
#Consumes(MediaType.APPLICATION_JSON)
public String insertSetup(SetupBean bean)
{
System.out.println("Printed");
SetupInterface setupInterface = new SetupImpl();
String insertSetup = setupInterface.insertSetup(bean);
return insertSetup;
}
}
Below is how I call this method using Java Jersey in my computer.
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8080/TestApp/rest/setup").path("/insertSetup");
SetupBean setupBean = new SetupBean();
setupBean.setIdPatient(1);
setupBean.setCircleType(1);
target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(setupBean, MediaType.APPLICATION_JSON_TYPE));
However, Now this method should be called in Android as well, but I'm not sure how to do that. I know how to make GET calls in android like below.
public static String httpGet(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn =
(HttpURLConnection) url.openConnection();
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
But since my method is POST and since it accept a Java Bean and it does return a String, how can I handle this in Android? Not interested using Jersey in android as it does have bad comments in Android environment.
Android provides a way to do what you want, but this is not a productive way, i like to use retrofit 2 to power my development and to write a better code.
Here a example of retrofit 2 that can help you =) :
add to your dependencies in build.gradle
dependencies {
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
}
Create your retrofit builder that specifies a converter and a base url.
public static final String URL = "http://localhost:8080/TestApp/rest/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Now create a Interface that will encapsulate your rest methods like below
public interface YourEndpoints {
#POST("setup/insertSetup")
Call<ResponseBody> insertSetup(#Body SetupBean setupBean);
}
Associate your endpoints interface with your retrofit instance.
YourEndpoints request = retrofit.create(YourEndpoints.class);
Call<ResponseBody> yourResult = request.insertSetup(YourSetupBeanObject);
yourResult.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//response.code()
//your string response response.body().string()
}
#Override
public void onFailure(Throwable t) {
//do what you have to do if it return a error
}
});
Ref to this links for more information:
http://square.github.io/retrofit/
https://github.com/codepath/android_guides/wiki/Consuming-APIs-with-Retrofit
that`s the code for the normal way you want
InputStream is = null;
OutputStream os = null;
HttpURLConnection con = null;
try {
//constants
URL url = new URL("http://localhost:8080/TestApp/rest/");
//Map your object to JSONObject and convert it to a json string
String message = new JSONObject().toString();
con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(1000);
con.setConnectTimeout(15000);
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setFixedLengthStreamingMode(message.getBytes().length);
con.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//open
con.connect();
//setup send
os = new BufferedOutputStream(con.getOutputStream());
os.write(message.getBytes());
//clean up
os.flush();
//do somehting with response
is = con.getInputStream();
String contentAsString = readData(is,len);
os.close();
is.close();
con.disconnect();
} catch (Exception e){
try {
os.close();
is.close();
con.disconnect();
} catch (IOException e1) {
e1.printStackTrace();
}
}
My issue is with the writeArgsToConn() function.....i think. I cant figure out how to implement it.
I am trying to post multipart-formdata from an Android device using AsyncTask class. Can anyone help with this? I want to stay away from the depreciated org.apache.http.legacy stuff and stick with up-to-date Android libraries.
I was able to use similar implementation for a class called DoPostJSON which used Content-Type: application/json and that class works fine.
Same question but on Reddit: https://redd.it/49qqyq
I had issues with getting nodejs express server to detect the parameters being sent in. My DoPostJSON class worked fine and my nodejs server was able to detect parameters...for some reason DoPostMultiPart doesnt work and nodejs server cant see paramters being passed in. I feel like I am using the library the wrong way.
public class DoPostMultiPart extends AsyncTask<JSONObject, Void, JSONObject> implements Post{
#Override
public HttpURLConnection createConn(String action) throws Exception{
URL url = new URL(Utils.host_api + action);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setReadTimeout(35000);
conn.setConnectTimeout(35000);
return conn;
}
#Override
public JSONObject getResponse(HttpURLConnection conn) throws Exception {
int responseCode = conn.getResponseCode();
String response = "";
if (responseCode == HttpsURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(in));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null)
stringBuilder.append(line).append("\n");
responseStreamReader.close();
response = stringBuilder.toString();
} else {
throw new Exception("response code: " + responseCode);
}
conn.disconnect();
return new JSONObject(response);
}
// TODO: fix this function
#Override
public void writeArgsToConn(JSONObject args, HttpURLConnection conn) throws Exception {
// define paramaters
String fullname = args.getString("fullname");
String email = args.getString("email");
String password = args.getString("password");
String confpassword = args.getString("confpassword");
Bitmap pic = (Bitmap) args.get("pic");
// plugin paramters into request
OutputStream os = conn.getOutputStream();
// how do I plugin the String paramters???
pic.compress(Bitmap.CompressFormat.JPEG, 100, os); // is this right???
os.flush();
os.close();
}
#Override
protected JSONObject doInBackground(JSONObject... params) {
JSONObject args = params[0];
try {
String action = args.getString("action");
HttpURLConnection conn = createConn(action);
writeArgsToConn(args, conn);
return getResponse(conn);
} catch (Exception e) {
Utils.logStackTrace(e);
return null;
}
}
}
I solved my issue by using OkHttpClient library.
JSONObject args = params[0];
try
{
final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("fullname", args.getString("fullname"))
.addFormDataPart("email", args.getString("email"))
.addFormDataPart("password", args.getString("password"))
.addFormDataPart("confpassword", args.getString("confpassword"))
.addFormDataPart("pic", "profile.png", RequestBody.create(MEDIA_TYPE_PNG, (File) args.get("pic")))
.build();
Request request = new Request.Builder()
.url(Utils.host_api + args.getString("action"))
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
return new JSONObject(response.body().string());
}
catch (Exception e)
{
Utils.logStackTrace(e);
return null;
}
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.