I want to execute java web service method from android app. My web service method signature looks like:
public String getData(String category) throws Exception
The method returns string and accepts a string as argument.
I have executed the method from google chrome's address bar as:
http://localhost:8080/JsonWebService/services/JsonWebService/getData?category=Marketing
Here getData is the name of the method and Marketing is the argument to that method. From explorer it works fine.
But when I add the same url to android app's httppost request it fails saying wrong number of arguments. My android app code is:
HttpPost post = new HttpPost("http://192.168.1.7:8080/JsonWebService/services/JsonWebService/getData?category=Marketing");
HttpResponse httpres = httpClient.execute(post);
Please Note: Here 192.168.1.7 is required as I am executing the app directly on the device and hence I am not using localhost.
A non argument method executes correctly from android app also.
But when argument is inserted in the url why it fails saying wrong number of arguments in android app and how it executes correctly in google chrome on PC. Please help... Thanks...
I am adding the code here. My java web service code is as follows:
public class JsonWebService {
#POST
#Path("getData")
public String getData(String category) throws Exception {
JSONObject jsonData = new JSONObject();
String Email = "";
String Name = "";
String receivedCat = "";
boolean status = false;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/admindb","root","");
java.sql.PreparedStatement query = con.prepareStatement("SELECT * FROM sample WHERE Category =" + "'" + category + "'" + ";");
ResultSet result = query.executeQuery();
while(result.next()){
receivedCat = result.getString("Category");
Name = result.getString("Name");
Email = result.getString("Email");
}
if(receivedCat.equals(category)){
status = true;
jsonData.put("Name",Name);
jsonData.put("Email", Email);
jsonData.put("status", status);
}
}
catch(Exception e) {
e.printStackTrace();
}
return jsonData.toString();
}
My android client code looks as follows:
btnCategory = (Button)findViewById(R.id.button1);
txtCategory = (EditText)findViewById(R.id.editText1);
gridV = (GridView)findViewById(R.id.gridView1);
txtName = (EditText)findViewById(R.id.editText3);
txtEmail = (EditText)findViewById(R.id.editText2);
btnCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Thread netThread = new Thread() {
public void run() {
try {
final JSONObject receivedJson;// = new JSONObject();
String URL = "http://192.168.1.7:8080/JsonWebService/services/JsonWebService/getData?category=Marketing?";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
HttpResponse httpres = httpClient.execute(post);
HttpEntity entity = httpres.getEntity();
String json = EntityUtils.toString(entity).toString();
String parts[] = json.split("<ns:return>");
parts = parts[1].split("</ns:return>");
String jsonPart = parts[0];
receivedJson = new JSONObject(jsonPart);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
txtName.setText(receivedJson.getString("Name"));
txtEmail.setText(receivedJson.getString("Email"));
}
catch(Exception e){
}
}
};
netThread.start();
}
});
}
The problem is in the java client in String URL, which is the string of URL that calls the java web service method. Please help me...
Related
I am using Okhttp lib to send data to server. I want to set text and images in RequestBody. For uploading multiple image to server using Okhttp i follow this link. I have implemented that type of code in my app in another activity class and its work fine. I have checked this question that how to pass array in RequestBody.
My arrayList format is like this
blockList
{
block0
{
description0 = First block
image0 = {image1, image2}
video0 = videolink
disp_order0 = 0
block0 = 0
}
block1
{
description1 = second block
image1 = {image1,image2,image2}
video1 = videolink
disp_order1 = 1
block1 = 1
}
.....
}
My Requirement :-
Now i want to send multiple images as an array in single parameter. When i send first block then parameter names are description0,image0[],video1,disp_order and block0 and image0[] will contain first block images as array and same for other.
API is working fine because when i test in postman then i receive the data in server side. You can see in below..
Here is my java function that set the data in RequestBody and make a call to send that data on sever.
ProgressDialog pd;
private OkHttpClient client;
private void saveCastBoxOnServer(String castBoxTitle, String selectedCastBoxId, String selectedCategoryId,
String userId, String action, ArrayList<CastBoxBlock> blockList)
{
try
{
client = new OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.build();
ArrayList<CastBoxBlock> blockArrayList = blockList;
int blockSize = blockArrayList.size();
MultipartBody.Builder multipartBuilderNew = new MultipartBody.Builder().setType(MultipartBody.FORM);
for (int i = 0; i < blockSize; i++)
{
String description = blockArrayList.get(i).getBlockDescription();
String descriptionField = "description"+i;
multipartBuilderNew.addFormDataPart(descriptionField, description);
/**This is used for distribution of images and videos. After that set that
* Images and video in multipartBuilder.
**/
CastBoxBlock model = blockArrayList.get(i);
ArrayList<SelectedMediaModel> mediaModels = model.getSelectedMediaModelArrayList();
int mediaModelsSize = mediaModels.size();
String passingVideoUri = "";
String videoUri = "";
for (int j = 0; j < mediaModelsSize; j++)
{
String mediaType = mediaModels.get(j).getMediaType();
if (mediaType.equals(StringKeyConstant.mediaVideo))
{
videoUri = mediaModels.get(j).getMediaPath();
if (passingVideoUri.trim().length()==0){
passingVideoUri = videoUri;
}else{
passingVideoUri = passingVideoUri + "," + videoUri;
}
}
else if (mediaType.equals(StringKeyConstant.mediaImage))
{
String imagePath = mediaModels.get(j).getMediaPath();
File sourceFile = new File(imagePath);
/**Changes whether JPEG or PNG**/
final MediaType MEDIA_TYPE = MediaType.parse(
constant.getFileExt(imagePath).endsWith("png") ? "image/png" : "image/jpeg");
String imageName = System.currentTimeMillis() + j + "_block_img.jpg";
String imageField = "image"+i+"["+j+"]";
multipartBuilderNew.addFormDataPart(imageField,imageName,
RequestBody.create(MEDIA_TYPE, sourceFile));
}
}
/**This is used to set the {#videoUri} block of videos and send to sever**/
String videoField = "video"+i;
multipartBuilderNew.addFormDataPart(videoField, passingVideoUri);
/**This will set the {#display_order} in multipartBuilder**/
String displayOrderField = "disp_order"+i;
String displayOrder = blockArrayList.get(i).getBlockIndex();
multipartBuilderNew.addFormDataPart(displayOrderField, displayOrder);
/**This will set the {#block} value in multipartBuilder**/
String blockField = "block"+i;
String block = ""+i;
multipartBuilderNew.addFormDataPart(blockField, block);
}
pd = new ProgressDialog(activity);
pd.setCancelable(false);
pd.setMessage(getResources().getString(R.string.please_wait));
pd.show();
RequestBody formBody = multipartBuilderNew
.addFormDataPart("cast_title", castBoxTitle)
.addFormDataPart("user_id", userId)
.addFormDataPart("cast_box", selectedCastBoxId)
.addFormDataPart("category", selectedCategoryId)
.addFormDataPart("action", action)
.build();
Request request = new Request.Builder()
.url(ApiUtils.ADD_FETCH_USER_CAST)
.post(formBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "Get Api credential fail."+call.toString());
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException
{
try
{
if (pd != null){
pd.cancel();
pd.dismiss();
pd = null;
}
String castSavedResponse = response.body().string();
Log.i(TAG, "castSavedResponse = " + castSavedResponse);
}
catch (Exception e){
Log.e(TAG, "***Error : onResponse() method");
e.printStackTrace();
}
}
});
}
catch (Exception e){
Log.e(TAG, "***Error : saveCastBoxOnServer()");
e.printStackTrace();
}
}
Thanks in advance. If any one will help it would be very appreciate.
When i check your code then i note one things. I am no sure but i think you change your code on image[] place. you can just change your code as below. I hope this will help you and you got the solution.
Use this code
String imageField = "image"+i+"[]";
Instead of
String imageField = "image"+i+"["+j+"]";
when i passed simple images as an array in Okhttp then i do code as above. For uploading multiple images on server using Okhttp, i also follow this link as you follow.
In my app, I am calling a rest api command via an async task class I have made.
When I pass the string through the async task call like this
apiRequest = new APIRequest();
apiRequest.execute("https:api.my/api/url");
I get "Protocol not found: [Ljava.lang.String;#f51e848? ... ]" where the ... is the rest of my api call.
Inside my async class:
#Override
protected String doInBackground(String... str) {
try {
URL url = new URL(str + responseFormat + "&api_key=" + apiKey);
}
catch(Exception e) {
error = e.getMessage();
return null;
}
}
With this method, I get the error shown above. However, when I cut the string out of the apiRequest call, and paste it directly into the async task, it works perfectly.
Below, code is working with the cut and paste of the url.
apiRequest = new APIRequest();
apiRequest.execute();
Inside my async class:
#Override
protected String doInBackground(String... str) {
try {
URL url = new URL("https:api.my/api/url" + responseFormat + "&api_key=" + apiKey);
}
catch(Exception e) {
error = e.getMessage();
return null;
}
}
I am trying to do a post to web api from android. The below is the code that I am using in android. The code is running without exception however the data is not inserted to the database. I included the code that I am using.
#Override
protected List doInBackground(Void... params)
{
List userDetails3 = new ArrayList();
URL url = null;
String urlshared = "http://10.0.0.9/MyWebApi/api/Student/PostAddStudent?userName="+"s4"+"&"+"password="+"1234"+"&"+"firsName="+"z"+"&"+"lastName="+"g"+"&"+"telephone="+"9160000000"+"&"+"address="+"2300 xxx"+"&"+"aliasMailId="+"s1.xx"+"&"+"emailId="+"xx#gmail.com"+"&"+"skypeId="+"z.g"+"";
try {
url = new URL(urlshared);
}
catch (MalformedURLException exception)
{
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
DataOutputStream dataOutputStream = null;
try
{
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestMethod("POST");
PrintWriter out = new PrintWriter(httpURLConnection.getOutputStream()); // this code is executed without exception
}
catch (IOException exception)
{
exception.printStackTrace();
}
return userDetails3; // (in debug) the code will run successfuly till here without exception
}
I am trying to access the PostAddStudent in the webapi. The below is my implementation of the controller and I excluded the codes inside the methods. For your information, I did test "PostAddStudent" and the other methods in the RegisterController by using the postman and they are working fine and the data inserted to database.
public class RegisterController : ApiController
{
public IEnumerable<Register> GetRegisterAuth(string userName,string password)
{
//return instance of register
}
public IEnumerable<Register> GetRegisterByUserName(string userName)
{
//return instance of register
}
public HttpResponseMessage PostAddInstructor(string instUserName, string instPassword, string instFirsName, string instLastName, string instTelephone, string instAddress, string instAliasMailId, string instEmailId, string instSkypeId)
{
//add to database and if okay will return System.Net.HttpStatusCode.Created
var response = Request.CreateResponse<Instructor>(System.Net.HttpStatusCode.Created, inst);
//if error exist then just return Badrequest
var response = Request.CreateResponse<Instructor>(System.Net.HttpStatusCode.BadRequest, inst);
}
public HttpResponseMessage PostAddStudent(string userName, string password, string firsName, string lastName, string telephone, string address, string aliasMailId, string emailId, string skypeId)
{
//add to database and if okay will return System.Net.HttpStatusCode.Created
var response = Request.CreateResponse<Instructor>(System.Net.HttpStatusCode.Created, inst);
//if error exist then just return Badrequest
var response = Request.CreateResponse<Instructor>(System.Net.HttpStatusCode.BadRequest, inst);
}
}
the below is the RouteConfig
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
//config.EnableSystemDiagnosticsTracing();
}
}
the below is the WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
I need the android code that can do the post to PostAddStudent.
thanks
Now in my app i try to do http parsing from url, but i didn't carry about threads, before this time...
I have such class and method:
public class TwitterOAuthHelper {
public String httpQueryToApi(String url) {
HttpGet get = new HttpGet(url);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setUseExpectContinue(params, false);
get.setParams(params);
String response = null;
try {
SharedPreferences settings = context.getSharedPreferences("my_app", 0);
String userKey = settings.getString("user_key", "");
String userSecret = settings.getString("user_secret", "");
consumer.setTokenWithSecret(userKey, userSecret);
consumer.sign(get);
DefaultHttpClient client = new DefaultHttpClient();
response = client.execute(get, new BasicResponseHandler());
} catch (Exception e) {
displayToast("Failed to get data.");
}
return response;
}
}
and now i try to move this logic into asyncTask:
String result;
public String httpQueryToApi(String url) {
new AsyncTask<String,Void,String>(){
#Override
protected String doInBackground(String... params) {
HttpGet get = new HttpGet(String.valueOf(params));
HttpParams param = new BasicHttpParams();
HttpProtocolParams.setUseExpectContinue(param, false);
get.setParams(param);
String response = null;
try {
SharedPreferences settings = context.getSharedPreferences("my_app", 0);
String userKey = settings.getString("user_key", "");
String userSecret = settings.getString("user_secret", "");
consumer.setTokenWithSecret(userKey, userSecret);
consumer.sign(get);
DefaultHttpClient client = new DefaultHttpClient();
response = client.execute(get, new BasicResponseHandler());
} catch (Exception e) {
displayToast("Failed to get data.");
}
result = response;
return response;
}
}.execute(url);
return result;
}
but how can i return my response result value to method?
what is the best practice of doing that?
dd below method to asynctask body (below doInBackground method):
#Override
protected void onPostExecute(String result) {
// result is your returned value from doInBackground
// now we are in main ui thread
}
If you want a callback to antoher method it should be interface
public interface ResultInterface {
public void resultFromHttp(String result);
}
then your method
public String httpQueryToApi(String url, final ResultInterface ri){
//as bove
#Override
protected void onPostExecute(String result) {
if(ri!=null)
ri.resultFromHttp(result);
}
}
implement ResultInterface in your Activity/Fragment/whatever is calling httpQueryToApi, pass this as second param (ri interface)
You can't since the Task will be executed in another thread.
However you could use a callback to get the result.
Take a look at: https://stackoverflow.com/a/19520293/4299154.
Initially your function returned a string which you then further processed. Fine.
But you can not use threading like that. You can not return result from the function, because it has not been set yet (well you can but it will return null). The correct way of doing this is
public void httpQueryToApi(String url) {
new AsyncTask<String,Void,String>(){
#Override
protected String doInBackground(String... params) {
HttpGet get = new HttpGet(String.valueOf(params));
HttpParams param = new BasicHttpParams();
HttpProtocolParams.setUseExpectContinue(param, false);
get.setParams(param);
String response = null;
try {
SharedPreferences settings = context.getSharedPreferences("my_app", 0);
String userKey = settings.getString("user_key", "");
String userSecret = settings.getString("user_secret", "");
consumer.setTokenWithSecret(userKey, userSecret);
consumer.sign(get);
DefaultHttpClient client = new DefaultHttpClient();
response = client.execute(get, new BasicResponseHandler());
} catch (Exception e) {
displayToast("Failed to get data.");
}
return response;
}
#Override
protected void onPostExecute(String s) {
//here s is the response string, do what ever you want
super.onPostExecute(s);
}
}.execute(url);
}
You will have to shift your further processing logic to onPostExecute, no other way :)
If you want do dig a little deeper look into Future<>
1) Create separate class for you Async (not anonymous).
2) Create interface class.
public interface AsyncResponse {
void onProcessFinish(String output);
}
3) In your Async class, you need to declare it (interface : AsyncResponse):
public class MyAsyncTask extends AsyncTask<String,Void,String>(){
public AsyncResponse listener = null;
public MyAsyncTask(AsyncResponse l) {
this.listener = l;
}
{...}
#Override
protected String doInBackground(String... params) {
HttpGet get = new HttpGet(String.valueOf(params));
HttpParams param = new BasicHttpParams();
HttpProtocolParams.setUseExpectContinue(param, false);
get.setParams(param);
String response = null;
try {
SharedPreferences settings = context.getSharedPreferences("my_app", 0);
String userKey = settings.getString("user_key", "");
String userSecret = settings.getString("user_secret", "");
consumer.setTokenWithSecret(userKey, userSecret);
consumer.sign(get);
DefaultHttpClient client = new DefaultHttpClient();
response = client.execute(get, new BasicResponseHandler());
} catch (Exception e) {
displayToast("Failed to get data.");
}
result = response;
return response;
}
#Override
protected void onPostExecute(String result) {
listener.onProcessFinish(result);
}
}
4) In your class (where you call AssyncClass, for example in your Activity) you need to implements interface you created earlier AsyncResponse.
public class MainActivity implements AsyncResponse{
{...}
void onProcessFinish(String output){
//this you will received result fired from async class of onPostExecute(result) method.
}
}
6) now you can call in MainActivity:
new MyAsyncTask(this).execute("your_url");
I am using commons HttpClient to make an http call to a Spring servlet. I need to add a few parameters in the query string. So I do the following:
HttpRequestBase request = new HttpGet(url);
HttpParams params = new BasicHttpParams();
params.setParameter("key1", "value1");
params.setParameter("key2", "value2");
params.setParameter("key3", "value3");
request.setParams(params);
HttpClient httpClient = new DefaultHttpClient();
httpClient.execute(request);
However when i try to read the parameter in the servlet using
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getParameter("key");
it returns null. In fact the parameterMap is completely empty. When I manually append the parameters to the url before creating the HttpGet request, the parameters are available in the servlet. Same when I hit the servlet from the browser using the URL with queryString appended.
What's the error here? In httpclient 3.x, GetMethod had a setQueryString() method to append the querystring. What's the equivalent in 4.x?
Here is how you would add query string parameters using HttpClient 4.2 and later:
URIBuilder builder = new URIBuilder("http://example.com/");
builder.setParameter("parts", "all").setParameter("action", "finish");
HttpPost post = new HttpPost(builder.build());
The resulting URI would look like:
http://example.com/?parts=all&action=finish
If you want to add a query parameter after you have created the request, try casting the HttpRequest to a HttpBaseRequest. Then you can change the URI of the casted request:
HttpGet someHttpGet = new HttpGet("http://google.de");
URI uri = new URIBuilder(someHttpGet.getURI()).addParameter("q",
"That was easy!").build();
((HttpRequestBase) someHttpGet).setURI(uri);
The HttpParams interface isn't there for specifying query string parameters, it's for specifying runtime behaviour of the HttpClient object.
If you want to pass query string parameters, you need to assemble them on the URL yourself, e.g.
new HttpGet(url + "key1=" + value1 + ...);
Remember to encode the values first (using URLEncoder).
I am using httpclient 4.4.
For solr query I used the following way and it worked.
NameValuePair nv2 = new BasicNameValuePair("fq","(active:true) AND (category:Fruit OR category1:Vegetable)");
nvPairList.add(nv2);
NameValuePair nv3 = new BasicNameValuePair("wt","json");
nvPairList.add(nv3);
NameValuePair nv4 = new BasicNameValuePair("start","0");
nvPairList.add(nv4);
NameValuePair nv5 = new BasicNameValuePair("rows","10");
nvPairList.add(nv5);
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
URI uri = new URIBuilder(request.getURI()).addParameters(nvPairList).build();
request.setURI(uri);
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() != 200) {
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output .... ");
String respStr = "";
while ((output = br.readLine()) != null) {
respStr = respStr + output;
System.out.println(output);
}
This approach is ok but will not work for when you get params dynamically , sometimes 1, 2, 3 or more, just like a SOLR search query (for example)
Here is a more flexible solution. Crude but can be refined.
public static void main(String[] args) {
String host = "localhost";
String port = "9093";
String param = "/10-2014.01?description=cars&verbose=true&hl=true&hl.simple.pre=<b>&hl.simple.post=</b>";
String[] wholeString = param.split("\\?");
String theQueryString = wholeString.length > 1 ? wholeString[1] : "";
String SolrUrl = "http://" + host + ":" + port + "/mypublish-services/carclassifications/" + "loc";
GetMethod method = new GetMethod(SolrUrl );
if (theQueryString.equalsIgnoreCase("")) {
method.setQueryString(new NameValuePair[]{
});
} else {
String[] paramKeyValuesArray = theQueryString.split("&");
List<String> list = Arrays.asList(paramKeyValuesArray);
List<NameValuePair> nvPairList = new ArrayList<NameValuePair>();
for (String s : list) {
String[] nvPair = s.split("=");
String theKey = nvPair[0];
String theValue = nvPair[1];
NameValuePair nameValuePair = new NameValuePair(theKey, theValue);
nvPairList.add(nameValuePair);
}
NameValuePair[] nvPairArray = new NameValuePair[nvPairList.size()];
nvPairList.toArray(nvPairArray);
method.setQueryString(nvPairArray); // Encoding is taken care of here by setQueryString
}
}
This is how I implemented my URL builder.
I have created one Service class to provide the params for the URL
public interface ParamsProvider {
String queryProvider(List<BasicNameValuePair> params);
String bodyProvider(List<BasicNameValuePair> params);
}
The Implementation of methods are below
#Component
public class ParamsProviderImp implements ParamsProvider {
#Override
public String queryProvider(List<BasicNameValuePair> params) {
StringBuilder query = new StringBuilder();
AtomicBoolean first = new AtomicBoolean(true);
params.forEach(basicNameValuePair -> {
if (first.get()) {
query.append("?");
query.append(basicNameValuePair.toString());
first.set(false);
} else {
query.append("&");
query.append(basicNameValuePair.toString());
}
});
return query.toString();
}
#Override
public String bodyProvider(List<BasicNameValuePair> params) {
StringBuilder body = new StringBuilder();
AtomicBoolean first = new AtomicBoolean(true);
params.forEach(basicNameValuePair -> {
if (first.get()) {
body.append(basicNameValuePair.toString());
first.set(false);
} else {
body.append("&");
body.append(basicNameValuePair.toString());
}
});
return body.toString();
}
}
When we need the query params for our URL, I simply call the service and build it.
Example for that is below.
Class Mock{
#Autowired
ParamsProvider paramsProvider;
String url ="http://www.google.lk";
// For the query params price,type
List<BasicNameValuePair> queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("price", 100));
queryParameters.add(new BasicNameValuePair("type", "L"));
url = url+paramsProvider.queryProvider(queryParameters);
// You can use it in similar way to send the body params using the bodyProvider
}
Im using Java 8 and apache httpclient 4.5.13
HashMap<String, String> customParams = new HashMap<>();
customParams.put("param1", "ABC");
customParams.put("param2", "123");
URIBuilder uriBuilder = new URIBuilder(baseURL);
for (String paramKey : customParams.keySet()) {
uriBuilder.addParameter(paramKey, customParams.get(paramKey));
}
System.out.println(uriBuilder.build().toASCIIString()); // ENCODED URL
System.out.println(uriBuilder.build().toString); // NORMAL URL
Full example with DTO
public class HttpResponseDTO {
private Integer statusCode;
private String body;
private String errorMessage;
public Integer getStatusCode() {
return statusCode;
}
public void setStatusCode(Integer statusCode) {
this.statusCode = statusCode;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
/**
*
* #param destinationURL
* #param params
* #param headers
* #return HttpResponseDTO
*/
public static HttpResponseDTO get(String baseURL, Boolean encodeURL, HashMap<String, String> params, HashMap<String, String> headers) {
final HttpResponseDTO httpResponseDTO = new HttpResponseDTO();
// ADD PARAMS IF
if (params != null && Boolean.FALSE.equals(params.isEmpty())) {
URIBuilder uriBuilder;
try {
uriBuilder = new URIBuilder(baseURL);
for (String paramKey : params.keySet()) {
uriBuilder.addParameter(paramKey, params.get(paramKey));
}
// CODIFICAR URL ?
if (Boolean.TRUE.equals(encodeURL)) {
baseURL = uriBuilder.build().toASCIIString();
} else {
baseURL = uriBuilder.build().toString();
}
} catch (URISyntaxException e) {
httpResponseDTO.setStatusCode(500);
httpResponseDTO.setErrorMessage("ERROR AL CODIFICAR URL: " + e.getMessage());
return httpResponseDTO;
}
}
// HACER PETICION HTTP
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
final HttpGet get = new HttpGet(baseURL);
// ADD HEADERS
if (headers != null && Boolean.FALSE.equals(headers.isEmpty())) {
for (String headerKey : headers.keySet()) {
get.setHeader(headerKey, headers.get(headerKey));
}
}
try (CloseableHttpResponse response = httpClient.execute(get);) {
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
httpResponseDTO.setBody(EntityUtils.toString(httpEntity));
httpResponseDTO.setStatusCode(response.getStatusLine().getStatusCode());
}
} catch(Exception e) {
httpResponseDTO.setStatusCode(500);
httpResponseDTO.setErrorMessage(e.getMessage());
return httpResponseDTO;
}
} catch(Exception e) {
httpResponseDTO.setStatusCode(500);
httpResponseDTO.setErrorMessage(e.getMessage());
return httpResponseDTO;
}
return httpResponseDTO;
}