CXF message's context outside of interceptors - java

I'm sending a SOAP message using apache cxf and what I want is to get both request and response payloads after the call is finished. Currently I'm using two interceptors and put payloads into messages' context like that message.getExchange().put(ExchangeContextEnum.RESPONSE_PAYLOAD.toString(), new String(payload, Charset.forName(StandardCharsets.UTF_8.name())));.
I don't want to process them right away in the interceptor itself because I need requests and responses for the series of calls. Also, I'd like to avoid making any kind of storage for the sake of simplicity and not having to deal with possible concurrency issues.
Can I get those values after the call is finished or the context is completely lost at this point?
Some code:
webService.call(object)
//here i'd like to get payloads
Interceptor for response:
public class LogInInterceptor extends AbstractPhaseInterceptor<Message> {
public LogInInterceptor() {
super(Phase.RECEIVE);
}
#Override
public void handleMessage(Message message) throws Fault {
InputStream in = message.getContent(InputStream.class);
byte payload[] = new byte[0];
try {
payload = IOUtils.readBytesFromStream(in);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayInputStream bin = new ByteArrayInputStream(payload);
message.setContent(InputStream.class, bin);
message.getExchange().put(ExchangeContextEnum.RESPONSE_PAYLOAD.toString(), new String(payload, Charset.forName(StandardCharsets.UTF_8.name())));
}
}
Interceptor for request:
public class WSSLogOutInterceptor extends AbstractSoapInterceptor {
public WSSLogOutInterceptor() {
super(Phase.USER_PROTOCOL);
}
#Override
public void handleMessage(SoapMessage message) throws Fault {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
SOAPMessage messageContent = message.getContent(SOAPMessage.class);
messageContent.writeTo(baos);
message.getExchange().put(ExchangeContextEnum.REQUEST_PAYLOAD.toString(), baos.toString());
} catch (SOAPException | IOException e) {
throw new Fault(e);
}
}
}

I ended up with the following solution:
Instead of putting values in message's exchange i simply do message.put(key, value) in the interceptor. To get those values after the call you
need to get response context like that (String) ((BindingProvider) webService).getResponseContext().get(key) where key is the same value you used before to put payload in the message. Now here's the problem - you won't find values that you put in the outgoing chain in response context. You can use simple workaround and put value in the exchange of the message and then, in the ingoing chain get it and put it into message. Pay attention to the phase I used (POST_PROTOCOL), it'd helpful if you use WSS.
Here's the code:
public class LoggingOutPayloadInterceptor extends AbstractSoapInterceptor {
public static final String OUT_PAYLOAD_KEY = "use.your.package.name.OUT_PAYLOAD_KEY";
public LoggingOutPayloadInterceptor() {
super(Phase.POST_PROTOCOL);
}
#Override
public void handleMessage(SoapMessage soapMessage) throws Fault {
Document document = soapMessage.getContent(SOAPMessage.class).getSOAPPart();
StringWriter stringWriter = new StringWriter();
try {
TransformerFactory.newInstance().newTransformer().transform(new DOMSource(document), new StreamResult(stringWriter));
} catch (TransformerException e) {
e.printStackTrace();
}
soapMessage.getExchange().put(OUT_PAYLOAD_KEY, stringWriter.toString());
}
}
public class LoggingInPayloadInterceptor extends AbstractSoapInterceptor {
public static final String IN_PAYLOAD_KEY = "use.your.package.name.IN_PAYLOAD";
public LoggingInPayloadInterceptor() {
super(Phase.POST_PROTOCOL);
addAfter(SAAJInInterceptor.class.getName());
}
#Override
public void handleMessage(SoapMessage message) throws Fault {
Document document = message.getContent(SOAPMessage.class).getSOAPPart();
StringWriter stringWriter = new StringWriter();
try {
TransformerFactory.newInstance().newTransformer().transform(new DOMSource(document), new StreamResult(stringWriter));
} catch (TransformerException e) {
e.printStackTrace();
}
message.put(IN_PAYLOAD_KEY, stringWriter.toString());
message.put(LoggingOutPayloadInterceptor.OUT_PAYLOAD_KEY, message.getExchange().get(LoggingOutPayloadInterceptor.OUT_PAYLOAD_KEY));
}
}
webService.call(...);
String inPayload = (String)((BindingProvider)webService).getResponseContext().get(LoggingInPayloadInterceptor.IN_PAYLOAD_KEY);
String outPayload = (String) ((BindingProvider) webService).getResponseContext().get(LoggingOutPayloadInterceptor.OUT_PAYLOAD_KEY);

Related

Freemarker encoding wrong

I have project it's jetty server which use freemarker. I use russian letters in my templates and receive ?. All subjects i have read before didn't help me.
I use in my code
.setContentType("text/html;charset=utf-8");
.setCharacterEncoding("UTF-8");
all my files is utf-8.
My Freemarker page genertor servlet
public class PageGenerator {
private static PageGenerator pageGenerator;
private Configuration cfg;
public static PageGenerator instance() {
if (pageGenerator == null)
pageGenerator = new PageGenerator();
return pageGenerator;
}
public String getPage(String filename, Map<String, Object> data) {
Writer stream = new StringWriter();
try {
Template template = cfg.getTemplate(filename);
template.process(data, stream);
} catch (IOException | TemplateException e) {
e.printStackTrace();
}
return stream.toString();
}
private PageGenerator() {
cfg = setCfg();
}
private Configuration setCfg(){
cfg = new Configuration(Configuration.VERSION_2_3_20);
try {
cfg.setDirectoryForTemplateLoading(new File("templates/"));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
} catch (IOException e) {
e.printStackTrace();
}
return cfg;
}
}
But in brouser my page in windows-1252 encoding.
Thanks for idea ddekany I used debag mode and find out that Class Response that extends HttpServletResponse has "magic" method .setCharacterEncoding() which set Character Encoding in response stream

Creating a Network Thread as a Method

I'm very new at programming for Android - please bear with me.
I'm building an app that requires network access, using OKHttp. Since I will be making many similarly structured requests from my server, I created a class that handles all network-related tasks, as I like to keep things compartmentalized.
One method I'm working on is createNetworkThread from within my NetworkManager class. This particular method takes three arguments:
Context context, final String requestURI, final RequestBody formParameters
What I need assistance with is how to return the data received from this method so I can use and manipulate it in the calling Activity.
Here is the method in question:
public void createNetworkThread(Context context, final String requestURI, final RequestBody formParameters) {
if (!this.isConnected(context)) return;
Runnable runnable = new Runnable() {
#Override
public void run() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(requestURI).post(formParameters).build();
Response response = null;
// Send login request, get response //
try {
response = client.newCall(request).execute();
String stringResponse = response.body().string();
JSONObject jsonResponse = new JSONObject(stringResponse);
Log.d("Net", "Request send and received!");
} catch (IOException e) {
Log.d("Net", "Failed");
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
Here is the call from the Activity:
final NetworkManager Net = new NetworkManager(this);
...
final String requestURI = "http://192.168.1.111/videonow.club/apprequest/signup/thread.php";
final RequestBody formVars = new FormBody.Builder().add("email", strEmail).add("password", strPass1).add("first_name", strNameFirst).add("last_name", strNameLast).build();
Net.createNetworkThread(SignupActivity.this, requestURI, formVars);
What I need to know is how to get the JSON data from jsonResponse returned from the method (I know void doesn't allow this) so I can use the data.
Would it be better to have the jsonObject returned so I can use something like this:
SomeType response = Net.createNetworkThread(...);
Or, to have a class variable within NetworkManager that would be set by the method so it would be called to and referenced like this:
Net.createNetworkThread(...);
SomeType response = Net.someVariable;
Or is there some much more reasonable way to receive this data?
I'm also calling new OkHttpClient() twice - once in the activity, so I can build the requestBody post variables, as well as in the NetworkManager class itself. My instincts tell me this is redundant... if so, is there a way to make this more efficient?
Thanks in advance!
You can use OkHttp with AysncTask like this:
public class Webservice extends AsyncTask<String, String, UserResponse> {
private String TAG = Webservice.class.getSimpleName();
private static final String ENDPOINT = "YOUR_URL";
private static final Moshi MOSHI = new Moshi.Builder().build();
private static final JsonAdapter<UserResponse> CONTRIBUTORS_JSON_ADAPTER_RESPONSE = MOSHI.adapter(Types.newParameterizedType(UserResponse.class, UserResponse.class));
UserResponse webResponse;
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
String postBody = "postBody\n";
#Override
protected UserResponse doInBackground(String... parmas) {
OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
Call call = okHttpClient.build().newCall(new Request.Builder()
.url(ENDPOINT)
.post(RequestBody.create(JSON, postBody))
.addHeader("Content-Type", "application/json")
.build());
try {
Response response = call.execute();
adModelResponse = CONTRIBUTORS_JSON_ADAPTER_RESPONSE.fromJson(response.body().source());
} catch (IOException e) {
e.printStackTrace();
}
return webResponse;
}
#Override
protected void onPostExecute(UserResponse adModelResponse) {
}
}
And then in Activity call like this:
Webservice webservice = new Webservice();
webservice.execute("YOUR_PARAMETER");
Libraries Used:
okhttp-3.2.0, moshi-1.1.0, okio-1.8.0
Make NetworkManager Abstract and add one abstract method say public abstract void onResult(JSONObject response); and override this method like
final NetworkManager Net = new NetworkManager(this){
#Override
public void onResult(JSONObject response){
//do whatever you want here
}
};
And from the createNetworkThread when finished call this method as
.....
response = client.newCall(request).execute();
String stringResponse = response.body().string();
JSONObject jsonResponse = new JSONObject(stringResponse);
onResult(jsonResponse);
......
You can use callback interface to get your data back to your activity. Consider the example below:
public interface JsonResponse {
onResponseReceived(JSONObject response);
}
Then your createNetworkThread will looks like this:
public void createNetworkThread(Context context, final String requestURI, final RequestBody formParameters, JsonResponse responseCallback) {
if (!this.isConnected(context)) return;
Runnable runnable = new Runnable() {
#Override
public void run() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(requestURI).post(formParameters).build();
Response response = null;
// Send login request, get response //
try {
response = client.newCall(request).execute();
String stringResponse = response.body().string();
JSONObject jsonResponse = new JSONObject(stringResponse);
responseCallback.onResponseReceived(jsonResponse); // This line will return to your caller
Log.d("Net", "Request send and received!");
} catch (IOException e) {
Log.d("Net", "Failed");
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
And finally the caller:
Net.createNetworkThread(SignupActivity.this, requestURI, formVars, new JsonResponse() {
#Override
public void onResponseReceived(JSONObject response) {
// Do stuff in your activity
// eventually use runOnUiThread for your UI operations
}
});

How to give parameters to a method which implements another method

I used a jersey server and I want that a endpoint redirect to the download of a file depending on parameters.
I have difficulties with the function below :
#GET
#Path("/get/{id}/{chunk}")
public Response getDescription(#PathParam("id") String id, #PathParam("chunk") String chunk) {
{
StreamingOutput fileStream = new StreamingOutput()
{
#Override
public void write(java.io.OutputStream output, String id) throws IOException, WebApplicationException
{
try
{
if (Objects.equals(chunk, new String("init"))) {
java.nio.file.Path path = Paths.get("src/main/uploads/example/frame_init.pdf");
}
else {
java.nio.file.Path path = Paths.get("src/main/uploads/example/"+ id +".pdf");
}
byte[] data = Files.readAllBytes(path);
output.write(data);
output.flush();
}
catch (Exception e)
{
throw new WebApplicationException("File Not Found !!");
}
}
};
return Response
.ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition","attachment; filename = myfile.pdf")
.build();
}
I have a problem with passing parameters to the function write. I have my parameters id and chunk by the endpoint but I can't use it in the write method because it implements StreamingOutput().
How I can handle it ? Thank you
For java, final keyword should solve your problem.
As updated code;
#GET
#Path("/get/{id}/{chunk}")
public Response getDescription(#PathParam("id") final String id, #PathParam("chunk") final String chunk) {
{
StreamingOutput fileStream = new StreamingOutput()
{
#Override
public void write(java.io.OutputStream output, String id2) throws IOException, WebApplicationException
{
try
{
if (Objects.equals(chunk, new String("init"))) {
java.nio.file.Path path = Paths.get("src/main/uploads/example/frame_init.pdf");
}
else {
java.nio.file.Path path = Paths.get("src/main/uploads/example/"+ id2 +".pdf");
}
byte[] data = Files.readAllBytes(path);
output.write(data);
output.flush();
}
catch (Exception e)
{
throw new WebApplicationException("File Not Found !!");
}
}
};
return Response
.ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition","attachment; filename = myfile.pdf")
.build();
}

Parsing XML from a website to a String array in Android please help me

Hello I am in the process of making an Android app that pulls some data from a Wiki, at first I was planning on finding a way to parse the HTML, but from something that someone pointed out to me is that XML would be much easier to work with. Now I am stuck trying to find a way to parse the XML correctly. I am trying to parse from a web address right now from:
http://zelda.wikia.com/api.php?action=query&list=categorymembers&cmtitle=Category:Games&cmlimit=500&format=xml
I am trying to get the titles of each of the games into a string array and I am having some trouble. I don't have an example of the code I was trying out, it was by using xmlpullparser. My app crashes everytime that I try to do anything with it. Would it be better to save the XML locally and parse from there? or would I be okay going from the web address? and how would I go about parsing this correctly into a string array? Please help me, and thank you for taking the time to read this.
If you need to see code or anything I can get it later tonight, I am just not near my PC at this time. Thank you.
Whenever you find yourself writing parser code for simple formats like the one in your example you're almost always doing something wrong and not using a suitable framework.
For instance - there's a set of simple helpers for parsing XML in the android.sax package included in the SDK and it just happens that the example you posted could be easily parsed like this:
public class WikiParser {
public static class Cm {
public String mPageId;
public String mNs;
public String mTitle;
}
private static class CmListener implements StartElementListener {
final List<Cm> mCms;
CmListener(List<Cm> cms) {
mCms = cms;
}
#Override
public void start(Attributes attributes) {
Cm cm = new Cm();
cm.mPageId = attributes.getValue("", "pageid");
cm.mNs = attributes.getValue("", "ns");
cm.mTitle = attributes.getValue("", "title");
mCms.add(cm);
}
}
public void parseInto(URL url, List<Cm> cms) throws IOException, SAXException {
HttpURLConnection con = (HttpURLConnection) url.openConnection();
try {
parseInto(new BufferedInputStream(con.getInputStream()), cms);
} finally {
con.disconnect();
}
}
public void parseInto(InputStream docStream, List<Cm> cms) throws IOException, SAXException {
RootElement api = new RootElement("api");
Element query = api.requireChild("query");
Element categoryMembers = query.requireChild("categorymembers");
Element cm = categoryMembers.requireChild("cm");
cm.setStartElementListener(new CmListener(cms));
Xml.parse(docStream, Encoding.UTF_8, api.getContentHandler());
}
}
Basically, called like this:
WikiParser p = new WikiParser();
ArrayList<WikiParser.Cm> res = new ArrayList<WikiParser.Cm>();
try {
p.parseInto(new URL("http://zelda.wikia.com/api.php?action=query&list=categorymembers&cmtitle=Category:Games&cmlimit=500&format=xml"), res);
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (SAXException e) {}
Edit: This is how you'd create a List<String> instead:
public class WikiParser {
private static class CmListener implements StartElementListener {
final List<String> mTitles;
CmListener(List<String> titles) {
mTitles = titles;
}
#Override
public void start(Attributes attributes) {
String title = attributes.getValue("", "title");
if (!TextUtils.isEmpty(title)) {
mTitles.add(title);
}
}
}
public void parseInto(URL url, List<String> titles) throws IOException, SAXException {
HttpURLConnection con = (HttpURLConnection) url.openConnection();
try {
parseInto(new BufferedInputStream(con.getInputStream()), titles);
} finally {
con.disconnect();
}
}
public void parseInto(InputStream docStream, List<String> titles) throws IOException, SAXException {
RootElement api = new RootElement("api");
Element query = api.requireChild("query");
Element categoryMembers = query.requireChild("categorymembers");
Element cm = categoryMembers.requireChild("cm");
cm.setStartElementListener(new CmListener(titles));
Xml.parse(docStream, Encoding.UTF_8, api.getContentHandler());
}
}
and then:
WikiParser p = new WikiParser();
ArrayList<String> titles = new ArrayList<String>();
try {
p.parseInto(new URL("http://zelda.wikia.com/api.php?action=query&list=categorymembers&cmtitle=Category:Games&cmlimit=500&format=xml"), titles);
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (SAXException e) {}

using dbpedia spotlight in java or scala

Does anyone know where to find a little how to on using dbpedia spotlight in java or scala? Or could anyone explain how it's done? I can't find any information on this...
The DBpedia Spotlight wiki pages would be a good place to start.
And I believe the installation page has listed the most popular ways (using a jar, or set up a web service) to use the application.
It includes instructions on using the Java/Scala API with your own installation, or calling the Web Service.
There are some additional data needed to be downloaded to run your own server for full service, good time to make a coffee for yourself.
you need download dbpedia spotlight (jar file) after that u can use next two classes ( author pablomendes ) i only make some change .
public class db extends AnnotationClient {
//private final static String API_URL = "http://jodaiber.dyndns.org:2222/";
private static String API_URL = "http://spotlight.dbpedia.org:80/";
private static double CONFIDENCE = 0.0;
private static int SUPPORT = 0;
private static String powered_by ="non";
private static String spotter ="CoOccurrenceBasedSelector";//"LingPipeSpotter"=Annotate all spots
//AtLeastOneNounSelector"=No verbs and adjs.
//"CoOccurrenceBasedSelector" =No 'common words'
//"NESpotter"=Only Per.,Org.,Loc.
private static String disambiguator ="Default";//Default ;Occurrences=Occurrence-centric;Document=Document-centric
private static String showScores ="yes";
#SuppressWarnings("static-access")
public void configiration(double CONFIDENCE,int SUPPORT,
String powered_by,String spotter,String disambiguator,String showScores){
this.CONFIDENCE=CONFIDENCE;
this.SUPPORT=SUPPORT;
this.powered_by=powered_by;
this.spotter=spotter;
this.disambiguator=disambiguator;
this.showScores=showScores;
}
public List<DBpediaResource> extract(Text text) throws AnnotationException {
LOG.info("Querying API.");
String spotlightResponse;
try {
String Query=API_URL + "rest/annotate/?" +
"confidence=" + CONFIDENCE
+ "&support=" + SUPPORT
+ "&spotter=" + spotter
+ "&disambiguator=" + disambiguator
+ "&showScores=" + showScores
+ "&powered_by=" + powered_by
+ "&text=" + URLEncoder.encode(text.text(), "utf-8");
LOG.info(Query);
GetMethod getMethod = new GetMethod(Query);
getMethod.addRequestHeader(new Header("Accept", "application/json"));
spotlightResponse = request(getMethod);
} catch (UnsupportedEncodingException e) {
throw new AnnotationException("Could not encode text.", e);
}
assert spotlightResponse != null;
JSONObject resultJSON = null;
JSONArray entities = null;
try {
resultJSON = new JSONObject(spotlightResponse);
entities = resultJSON.getJSONArray("Resources");
} catch (JSONException e) {
//throw new AnnotationException("Received invalid response from DBpedia Spotlight API.");
}
LinkedList<DBpediaResource> resources = new LinkedList<DBpediaResource>();
if(entities!=null)
for(int i = 0; i < entities.length(); i++) {
try {
JSONObject entity = entities.getJSONObject(i);
resources.add(
new DBpediaResource(entity.getString("#URI"),
Integer.parseInt(entity.getString("#support"))));
} catch (JSONException e) {
LOG.error("JSON exception "+e);
}
}
return resources;
}
}
second class
/**
* #author pablomendes
*/
public abstract class AnnotationClient {
public Logger LOG = Logger.getLogger(this.getClass());
private List<String> RES = new ArrayList<String>();
// Create an instance of HttpClient.
private static HttpClient client = new HttpClient();
public List<String> getResu(){
return RES;
}
public String request(HttpMethod method) throws AnnotationException {
String response = null;
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
LOG.error("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
response = new String(responseBody);
} catch (HttpException e) {
LOG.error("Fatal protocol violation: " + e.getMessage());
throw new AnnotationException("Protocol error executing HTTP request.",e);
} catch (IOException e) {
LOG.error("Fatal transport error: " + e.getMessage());
LOG.error(method.getQueryString());
throw new AnnotationException("Transport error executing HTTP request.",e);
} finally {
// Release the connection.
method.releaseConnection();
}
return response;
}
protected static String readFileAsString(String filePath) throws java.io.IOException{
return readFileAsString(new File(filePath));
}
protected static String readFileAsString(File file) throws IOException {
byte[] buffer = new byte[(int) file.length()];
#SuppressWarnings("resource")
BufferedInputStream f = new BufferedInputStream(new FileInputStream(file));
f.read(buffer);
return new String(buffer);
}
static abstract class LineParser {
public abstract String parse(String s) throws ParseException;
static class ManualDatasetLineParser extends LineParser {
public String parse(String s) throws ParseException {
return s.trim();
}
}
static class OccTSVLineParser extends LineParser {
public String parse(String s) throws ParseException {
String result = s;
try {
result = s.trim().split("\t")[3];
} catch (ArrayIndexOutOfBoundsException e) {
throw new ParseException(e.getMessage(), 3);
}
return result;
}
}
}
public void saveExtractedEntitiesSet(String Question, LineParser parser, int restartFrom) throws Exception {
String text = Question;
int i=0;
//int correct =0 ; int error = 0;int sum = 0;
for (String snippet: text.split("\n")) {
String s = parser.parse(snippet);
if (s!= null && !s.equals("")) {
i++;
if (i<restartFrom) continue;
List<DBpediaResource> entities = new ArrayList<DBpediaResource>();
try {
entities = extract(new Text(snippet.replaceAll("\\s+"," ")));
System.out.println(entities.get(0).getFullUri());
} catch (AnnotationException e) {
// error++;
LOG.error(e);
e.printStackTrace();
}
for (DBpediaResource e: entities) {
RES.add(e.uri());
}
}
}
}
public abstract List<DBpediaResource> extract(Text text) throws AnnotationException;
public void evaluate(String Question) throws Exception {
evaluateManual(Question,0);
}
public void evaluateManual(String Question, int restartFrom) throws Exception {
saveExtractedEntitiesSet(Question,new LineParser.ManualDatasetLineParser(), restartFrom);
}
}
main()
public static void main(String[] args) throws Exception {
String Question ="Is the Amazon river longer than the Nile River?";
db c = new db ();
c.configiration(0.0, 0, "non", "CoOccurrenceBasedSelector", "Default", "yes");
System.out.println("resource : "+c.getResu());
}
I just add one little fix for your answer.
Your code is running, if you add the evaluate method call:
public static void main(String[] args) throws Exception {
String question = "Is the Amazon river longer than the Nile River?";
db c = new db ();
c.configiration(0.0, 0, "non", "CoOccurrenceBasedSelector", "Default", "yes");
c.evaluate(question);
System.out.println("resource : "+c.getResu());
}
Lamine
In the request method of the second class (AnnotationClient) in Adel's answer, the author Pablo Mendes hasn't finished
TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
which is an annoying warning that needs to be removed by replacing
byte[] responseBody = method.getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
response = new String(responseBody);
with
Reader in = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8");
StringWriter writer = new StringWriter();
org.apache.commons.io.IOUtils.copy(in, writer);
response = writer.toString();

Categories

Resources