where is the wrong in this syntax of calling http request get - java

I have this call (from the browser)
http://serverName:8081/cmp-mg-?sub_x?=7
and it returns 200 response
and I want to call do that request from my web service:
this is my web service:
public Response sendMT2(#BeanParam MT mt) throws IOException {
try {
HttpHost host = new HttpHost("serverName", 8081);
HttpClient client = HttpClientBuilder.create().build();
HttpRequest request = new BasicHttpRequest("GET",
"/serverp/sam?" + mt.getURLParameter());
System.out.println("/cmp-mg-xconn-http-webapp/sam?"
+ mt.getURLParameter());
HttpResponse response = client.execute(host, request);
String responseString = new BasicResponseHandler()
.handleResponse(response);
return Response.ok(responseString).build();
} catch (ClientProtocolException e) {
throw e;
// return Response.status(500).build();
} catch (IOException e) {
throw e;
// return Response.status(500).build();
}
}
but I am getting error
org.apache.http.client.HttpResponseException: Not Found
what is the wrong?

I found the error myself.
before sub-r_mob .. i had ? instead of &

Related

Hiding the logs of an API call

I am making an http request using Httpclient and I need to hide logs for this specific API call as it contains sensitive data. We need the logs to be in debug level so lowering the log level is not an option is there a way that I can hide the logs of just this request?
public Boolean authenticate(String userName, String password) throws IOException {
HttpPost httpPost = new HttpPost(authServiceBaseUrl + AUTH_SERVICE_AUTH_URI);
try {
StringEntity httpEntity = new StringEntity(new JSONObject()
.put(USERNAME_ATTRIBUTE_NAME, userName)
.put(PASSWORD_ATTRIBUTE_NAME, password)
.toString());
httpEntity.setContentType(ContentType.APPLICATION_JSON.toString());
httpPost.setEntity(httpEntity);
} catch (Exception e) {
throw new Exception(logException(userName, "authenticate"), e );
}
try (CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = httpClient.execute(httpPost)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return Boolean.TRUE;
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
log.warnf("[%s] Authentication failed.", userName);
return Boolean.FALSE;
} else {
throw new UserAuthenticationException(
response.getStatusLine().getStatusCode(), userName,
"Error while trying to authenticate user");
}
} catch (UserAuthenticationException e) {
throw e;
} catch (Exception e) {
throw new Exception(logException(userName, "authenticate"), e);
}
}

Move CloseableHttpResponse inside nested try with resources

I have the following code using try with resources with CloseableHttpResponse
CloseableHttpResponse response = null;
try (CloseableHttpClient httpClient = HttpClients.custom().build()){
//code...
response = httpClient.execute(target, post);
String responseText = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
logger.error("Failed sending request", e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
logger.error("Failed releasing response", e);
}
}
}
Can I safely replace with nested try with resources:
try (CloseableHttpClient httpClient = HttpClients.custom().build()){
URIBuilder uriBuilder = new URIBuilder(url);
HttpHost target = new HttpHost(uriBuilder.getHost(), uriBuilder.getPort(), uriBuilder.getScheme());
HttpPost post = new HttpPost(uriBuilder.build());
try (CloseableHttpResponse response = httpClient.execute(target, post)) {
String responseText = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
logger.error("Failed sending request", e);
}
Or is it better to use a single try with resources block:
try (CloseableHttpClient httpClient = HttpClients.custom().build();
CloseableHttpResponse response = getResponse(httpClient, url)) {
Sometime refactoring to single block is problematic, so I wanted to know the a nested/additional block is a valid solution.
HttpClient never returns a null HttpResponse object. The first construct is simply not useful. Both the second and the third constructs are perfectly valid

Soap request creation using ksoap2 for multilevel tags

I want to build a soap request using KSOAP2 for android application. how to create a request for the given below soap request.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:glob="http://sap.com/xi/SAPGlobal20/Global"
xmlns:yrt="http://0021611689-one-off.sap.com/YRTWIVFXY_"
xmlns:ytk="http://0021611689-one-off.sap.com/YTK2PLNNY_"
xmlns:glob1="http://sap.com/xi/AP/Globalization">`
<soapenv:Header/>
<soapenv:Body>
<glob:CustomerBundleMaintainRequest_sync_V1>
<BasicMessageHeader>
</BasicMessageHeader>
<Customer>
<InternalID>234569</InternalID>
<!--Optional:-->
<CategoryCode>1</CategoryCode>
<CustomerIndicator>true</CustomerIndicator>
<!--Optional:-->
<LifeCycleStatusCode>2</LifeCycleStatusCode>
<!--Optional:-->
</Customer>
</glob:CustomerBundleMaintainRequest_sync_V1>
</soapenv:Body>
</soapenv:Envelope>
I have written the Android code and tried to build the request it shows an error that Soapfault message error. Find below the android code
public class CreateCustomer {
public void createCustomerAccount() throws IOException {
SoapObject soapObject = new SoapObject(NAME_SPACE,METHOD_NAME);
soapObject.addProperty("InternalID","98765");
soapObject.addProperty("CategoryCode","1");
soapObject.addProperty("CustomerIndicator","true");
soapObject.addProperty("LifeCycleStatusCode","2");
}
For Building soap request ..
public String sendSoapRequest(Context c) throws Exception {
String finalString = "Paste your whole request through which you can send request from browser sucessfully";
Log.i("TAG", "*********************** FinalString Before "
+ FinalString);
// send SOAP request
InputStream resInputStream = sendRequest(FinalString);
// create the response SOAP envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
// process SOAP response
parseResponse(resInputStream, envelope);
Object bodyIn = envelope.bodyIn;
SoapObject RequestSOAP = (SoapObject) envelope.bodyIn;
String response = RequestSOAP.getProperty(0).toString();
if (bodyIn instanceof SoapFault) {
throw (SoapFault) bodyIn;
}
return response.toString();
}
calling sendRequest ..
private InputStream sendRequest(String requestContent) throws Exception {
// initialize HTTP post
HttpPost httpPost = null;
try {
httpPost = new HttpPost(PostURL);
httpPost.addHeader("Content-Type", "text/xml;charset=UTF-8");
httpPost.addHeader("SOAPAction", "Your Soap Action");
} catch (Throwable e) {
Log.e("LOG_TAG", "Error initializing HTTP post for SOAP request", e);
// throw e;
}
// load content to be sent
try {
HttpEntity postEntity = new StringEntity(requestContent);
httpPost.setEntity(postEntity);
} catch (UnsupportedEncodingException e) {
Log.e("LOG_TAG",
"Unsupported ensoding of content for SOAP request", e);
throw e;
}
// send request
HttpResponse httpResponse = null;
HttpClient httpClient = new DefaultHttpClient();
try {
httpResponse = httpClient.execute(httpPost);
} catch (Throwable e) {
Log.e("LOG_TAG", "Error sending SOAP request", e);
// throw e;
}
// get SOAP response
try {
// get response code
int responseStatusCode = httpResponse.getStatusLine()
.getStatusCode();
// if the response code is not 200 - OK, or 500 - Internal error,
// then communication error occurred
if (responseStatusCode != 200 && responseStatusCode != 500) {
String errorMsg = "Got SOAP response code "
+ responseStatusCode + " "
+ httpResponse.getStatusLine().getReasonPhrase();
// ...
}
// get the response content
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
return is;
} catch (Throwable e) {
Log.e("LOG_TAG", "Error getting SOAP response", e);
// throw e;
}
return null;
}
call parseResponse
/**
* Parses the input stream from the response into SoapEnvelope object.
*/
private void parseResponse(InputStream is, SoapEnvelope envelope)
throws Exception {
try {
XmlPullParser xp = new KXmlParser();
xp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
xp.setInput(is, "UTF-8");
envelope.parse(xp);
} catch (Throwable e) {
Log.e("LOG_TAG", "Error reading/parsing SOAP response", e);
}
}
call SendOrderDetails...
private class SendOrderDetails extends AsyncTask<String, CartViewItemsBean, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg) {
String fdfd = "";
try {
fdfd = sendSoapRequest(getActivity());
} catch (Exception e) {
e.printStackTrace();
}
return fdfd;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i("transactionresponse", result);
if (!result.equalsIgnoreCase("")) {
try {
helpher.deleteTotalRecord();
String ffsd = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + result.toString();
XmlToJson xmlToJson = new XmlToJson.Builder(ffsd.trim()).build();
JSONObject jsonObject = xmlToJson.toJson();
} catch (Exception e) {
e.printStackTrace();
}
} else {
}
}
}
And you have to use library XmlToJson
finally you have to call this using
new SendOrderDetails().execute();

Retrieve response body from ClientResource

I try to issue a POST request with ClientResource, I'm able to retrieve the response STATUS, I also want to get the response body when I get an exception.
Here is my code:
public static Pair<Status, JSONObject> post(String url, JSONObject body) {
ClientResource clientResource = new ClientResource(url);
try {
Representation response = clientResource.post(new JsonRepresentation(body), MediaType.APPLICATION_JSON);
String responseBody = response.getText();
Status responseStatus = clientResource.getStatus();
return new ImmutablePair<>(responseStatus, new JSONObject(responseBody));
} catch (ResourceException e) {
logger.error("failed to issue a POST request. responseStatus=" + clientResource.getStatus().toString(), e);
//TODO - how do I get here the body of the response???
} catch (IOException |JSONException e) {
throw e;
} finally {
clientResource.release();
}
}
Here is the code that my server resource returns in case of failure
getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN);
JsonRepresentation response = new JsonRepresentation( (new JSONObject()).
put("result", "failed to execute") );
return response;
I try to catch the "result" with no success
In fact, the getResponseEntity method returns the content of the response. It corresponds to a representation. You can wrap it by a JsonRepresentation class if you expect some JSON content:
try {
(...)
} catch(ResourceException ex) {
Representation responseRepresentation
= clientResource.getResponseEntity();
JsonRepresentation jsonRepr
= new JsonRepresentation(responseRepresentation);
JSONObject errors = jsonRepr.getJsonObject();
}
You can notice that Restlet also supports annotated exceptions.
Otherwise I wrote a blog post about this subject: http://restlet.com/blog/2015/12/21/exception-handling-with-restlet-framework/. I think that it could help you.
Thierry

NetworkOnMainThreadException sometimes thrown

I try to get response from POST request. The problem is that sometimes I get NetworkOnMainThreadException although I'm using AsyncTask for the network communication. That means that sometimes I get the response successfully, and sometimes I get this exception.
Here is my HTTP POST request AsyncTask:
static class HTTPPostRequest extends AsyncTask<PostRequestParams, Void, AsyncResponse> {
#Override
protected AsyncResponse doInBackground(PostRequestParams... params) {
AsyncResponse retVal = new AsyncResponse();
HttpClient client = getHttpClient();
UrlEncodedFormEntity formEntity = null;
HttpPost request = new HttpPost();
try {
request.setURI(new URI(params[0].URL));
formEntity = new UrlEncodedFormEntity(params[0].params);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
retVal.setOutput(response);
} catch (ClientProtocolException e) {
retVal.setException(e);
} catch (IOException e) {
retVal.setException(e);
} catch (URISyntaxException e) {
retVal.setException(e);
}
return retVal;
}
}
And the code that actually call it:
AsyncResponse response = new AsyncResponse();
PostRequestParams postParams = new PostRequestParams();
postParams.URL = URL + "login.php";
postParams.params.add(new BasicNameValuePair("username", username));
postParams.params.add(new BasicNameValuePair("password", password));
try {
response = new HTTPPostRequest().execute(postParams).get();
if (response.getException() != null) {
return "Error";
}
HttpResponse httpResponse = (HttpResponse) response.getOutput();
if (httpResponse.getStatusLine().getStatusCode() != 200) {
return "Error " + httpResponse.getStatusLine().getStatusCode();
}
return (String) formatResponse(new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())));
} catch (InterruptedException | ExecutionException | IllegalStateException | IOException e) {
response.setException(e);
return null;
}
You should move the code that handles the InputStream, like:
return (String) formatResponse(new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())));
to your AsyncTask as well. Handling InputStreams is nothing that you want to do in your UI Thread.

Categories

Resources