Dear all i am using Loopj and really like it. It makes my life easier. Now I want post json in the body of the post request.kindly check it what i m doing wrong my code is below.
params.put("SaleOrderItems", mJsonArrayOfObject.toString());
params.put("CustomerReferenceNumber", "asdf");
// /*mSaleOrder.getmCustomerReferenceNo()*/);
params.put("RecordType", "HOS");
params.put("DeliveryDate", "2012-12-28T12:04:27.3553985+01:00"); // mSaleOrder.getmDeliveryDate());
params.put("SellToCustomerNumber", "user");
Then i call like this.
mAsyncHttpClient.post(WEBCONSTANTS.ORDER_SERVICE_SAVE_ORDER, mParams,
new AsyncHttpResponseHandler(){};
I got this error
{"Message":"No HTTP resource was found that matches the request URI}
Kindly tell me how to send json array of objects in the body of the post request using LoopJ.
best regards,
I think this is what you're looking for:
String url = "<your site url>";
JSONObject jdata = new JSONObject();
try {
jdata.put("key1", val1);
jdata.put("key2", val2);
} catch (Exception ex) {
// json exception
}
StringEntity entity;
try {
entity = new StringEntity(jdata.toString());
client.post(getBaseContext(), url, entity, "application/json", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
JSONObject res;
try {
res = new JSONObject(response);
Log.d("debug", res.getString("some_key")); // this is how you get a value out
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Related
I have json response from elasticsearch rest client. I would like to create elasticsearch SearchResponse or GetResponse object from that string(json), so that I can reuse un-marshaling part from the grails-2.4.3 elasticsearch plugin.Can some one help me on that ?
I'm not sure if this question is still relevant, but this one worked for me:
String responseJson = "{\"took\":5,\"timed_out\":false,\"_shards\".....}";
try {
JsonXContentParser xContentParser = new JsonXContentParser(NamedXContentRegistry.EMPTY,
new JsonFactory().createParser(responseJson));
SearchResponse response = SearchResponse.fromXContent(xContentParser);
...
Do Whatever
...
} catch (IOException e) {
handleException....
}
I did manage to find something that may help you.
I wrote an JSON like this:
XContentBuilder builder = XContentFactory.jsonBuilder();
response.toXContent(builder, ToXContent.EMPTY_PARAMS);
String result = Strings.toString(builder);
and then I manged to read it like this:
try {
NamedXContentRegistry registry = new NamedXContentRegistry(getDefaultNamedXContents());
XContentParser parser = JsonXContent.jsonXContent.createParser(registry, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, result);
SearchResponse searchResponse = SearchResponse.fromXContent(parser);
} catch (IOException e) {
System.out.println("exception " + e);
} catch (Exception e) {
System.out.println("exception " + e);
}
public static List<NamedXContentRegistry.Entry> getDefaultNamedXContents() {
Map<String, ContextParser<Object, ? extends Aggregation>> map = new HashMap<>();
map.put(TopHitsAggregationBuilder.NAME, (p, c) -> ParsedTopHits.fromXContent(p, (String) c));
map.put(StringTerms.NAME, (p, c) -> ParsedStringTerms.fromXContent(p, (String) c));
List<NamedXContentRegistry.Entry> entries = map.entrySet().stream()
.map(entry -> new NamedXContentRegistry.Entry(Aggregation.class, new ParseField(entry.getKey()), entry.getValue()))
.collect(Collectors.toList());
return entries;
}
Hope it works :)
I got Page source using
String pageSource = driver.getPageSource();
Now i need to save this xml file to local in cache. So i need to get element attributes like x and y attribute value rather than every time get using element.getAttribute("x");. But I am not able to parse pageSource xml file to some special character. I cannot remove this character because at if i need element value/text it shows different text if i will remove special character. Appium is use same way to do this.
I was also facing same issue and i got resolution using below code which i have written and it works fine
public static void removeEscapeCharacter(File xmlFile) {
String pattern = "(\\\"([^=])*\\\")";
String contentBuilder = null;
try {
contentBuilder = Files.toString(xmlFile, Charsets.UTF_8);
} catch (IOException e1) {
e1.printStackTrace();
}
if (contentBuilder == null)
return;
Pattern pattern2 = Pattern.compile(pattern);
Matcher matcher = pattern2.matcher(contentBuilder);
StrBuilder sb = new StrBuilder(contentBuilder);
while (matcher.find()) {
String str = matcher.group(1).substring(1, matcher.group(1).length() - 1);
try {
sb = sb.replaceFirst(StrMatcher.stringMatcher(str),
StringEscapeUtils.escapeXml(str));
} catch (Exception e) {
e.printStackTrace();
}
}
try {
Writer output = null;
output = new BufferedWriter(new FileWriter(xmlFile, false));
output.write(sb.toString());
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if you will get that kind of problem then catch it with remove special character and parse again.
try {
doc = db.parse(fileContent);
} catch (Exception e) {
removeEscapeCharacter(file);
doc = db.parse(file);
}
It might works for you.
I can able to do same using SAXParser and add handler to do for this.
Refer SAX Parser
this is the code i wrote to send the url request using a thread:
while(true)
{
String url="http://192.168.1.7:8084/SFTS/updateLocation.jsp?empid=12304&lat=16.23&lon=21.998;interface=wifi";
try{
StreamConnection conn = (StreamConnection)Connector.open(url, Connector.READ_WRITE);
conn.openInputStream();
Thread.sleep(30*1000);
conn.close();
}catch(Exception e)
{
e.printStackTrace();
}
try {
Thread.sleep(30*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
the code i used to this thread:
Calendar cal=Calendar.getInstance();
long time=cal.get(Calendar.HOUR);
add(new RichTextField(String.valueOf(time)));
(new test()).start();
by using this code i am able to send one request successfully but after that server is not receiving other request. please provide me a solution.
Firstly, when you're using a while loop like this, you shouldn't put the sleep within the try method.
while(true)
{
try{
String url="http://192.19.18.10:8084/SFTS/updateLocation.jsp?empid=12304&lat="+lan+".23&lon=21.998;interface=wifi";
StreamConnection conn = (StreamConnection)Connector.open(url, Connector.READ_WRITE);
conn.openInputStream();;
}catch(Exception e)
{
e.printStackTrace();
}
try {
Thread.sleep(30*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Secondly, you're constantly trying to create a new stream without first closing the previous connection. Either read up on how StreamConnection works effectively, or simply use ConnectionFactory and not StreamConnection.
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
if (connDesc != null) {
try {
HttpConnection httpConn;
httpConn = (HttpConnection) connDesc.getConnection();
httpConn.close();
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
The above is for OS 5 and above, in your case... as the connection seems to work the first time, in your existing code I would try simply closing the connection using:
conn.close();
The following code is used to get an XML file from a web server, and today, for the last few runs, this throws an exception with an error message "stream close." I have not modified this code since yesterday, nor have I modified any methods that handle the parsing.
The idea is this builds a list of item from the XML file pulled from the fullurl. There should 20 items in the list (based on the XML file I am using right now). In the last few runs, the parsing operation has thrown the exception mentioned above, and only stores 5 items. The method public void endDocument() never gets called.
Any thoughts would be helpful, since this will have to be moved to a background task, and I would like to have solved before I do that.
public void getAndParseXML() {
HttpConnection xmlcon = null;
InputStream xmlinput = null;
SAXParserFactory spf = null;
String fullurl = this.getNewsUrl() + NewsListBuilderTask.CONNECTION_STRING; // URL of XML file along specification for connection type
if ( (TransportInfo.isTransportTypeAvailable(TransportInfo.TRANSPORT_TCP_WIFI)) && (TransportInfo.hasSufficientCoverage(TransportInfo.TRANSPORT_TCP_WIFI)) )
fullurl += NewsListBuilderTask.WIFI_STRING;
try {
xmlcon = (HttpConnection)Connector.open( fullurl, Connector.READ, false ); // open connection to XML source
spf = SAXParserFactory.newInstance(); // set up xml parsers
xmlinput = xmlcon.openInputStream(); // set up input stream
SAXParser saxparser = spf.newSAXParser(); // create a new parser object
saxparser.parse( xmlinput, this ); // parse operations start here
}
catch( IOException ex ) {
System.out.println( "IOException Caught:\t" + ex.getMessage() ); // set a default item if any exception occurs with retreiving or parsing XML file
this.createDefaultItem();
}
catch (SAXException ex) {
System.out.println( "SAXException Caught:\t" + ex.getMessage() );
ex.printStackTrace();
this.createDefaultItem();
}
catch ( IllegalArgumentException ex ) {
System.out.println( "IllegalArgumentException Caught:\t" + ex.getMessage() );
ex.printStackTrace();
this.createDefaultItem();
}
catch (ParserConfigurationException ex) {
System.out.println( "ParserConfigurationException Caught:\t" + ex.getMessage() );
ex.printStackTrace();
this.createDefaultItem();
}
finally {
if ( xmlinput != null) {
try {
xmlinput.close(); // attempt to close all connections
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if ( xmlcon != null ) {
try {
xmlcon.close();
}
catch ( IOException ex ) {
ex.printStackTrace();
}
}
}
}
NOTE: The fullurl used ends up bieng "http://somexmlfile.com?type=photo;deviceside=true" with ";interface=wifi" appended if available.
I am using the following code to upload a video to Youtube through youtube API. My problem is after uploading the video, I need to give the location of the video to the user. How do I find this ?
I'll be really grateful if someone can help me to solve this.
MediaFileSource ms = new MediaFileSource(videoFile, mimeType);
String videoTitle = title;
VideoEntry newEntry = new VideoEntry();
YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();
mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, "Tech"));
mg.setTitle(new MediaTitle());
mg.getTitle().setPlainTextContent(videoTitle);
mg.setKeywords(new MediaKeywords());
mg.getKeywords().addKeyword("yt:crop=16:9");
mg.setDescription(new MediaDescription());
mg.getDescription().setHtmlContent(attributionDocument);
mg.setPrivate(true);
mg.setVideoId("Vid1");
ResumableGDataFileUploader uploader = null;
try {
uploader = new ResumableGDataFileUploader.Builder(
service, new URL(RESUMABLE_UPLOAD_URL), ms, newEntry)
.title(videoTitle)
.build();
uploader.start();
while (!uploader.isDone()) {
try {
Thread.sleep(PROGRESS_UPDATE_INTERVAL);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
switch(uploader.getUploadState()) {
case COMPLETE:
System.out.println("Uploaded successfully");
break;
case CLIENT_ERROR:
System.out.println("Upload Failed");
break;
default:
System.out.println("Unexpected upload status");
break;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
}
I managed to solve this by myself. Instead of using resumable file upload, I used direct upload. My code:
String id = "";
File videoFile = new File(videoLocation);
if (!videoFile.exists()) {
System.out.println("Sorry, that video doesn't exist.");
}
String videoTitle = title;
VideoEntry newEntry = new VideoEntry();
YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();
mg.setTitle(new MediaTitle());
mg.getTitle().setPlainTextContent(videoTitle);
mg.setKeywords(new MediaKeywords());
mg.getKeywords().addKeyword("yt:crop=16:9");
mg.setDescription(new MediaDescription());
mg.getDescription().setHtmlContent(attributionDocument);
mg.setPrivate(true);
mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, "Tech"));
MediaFileSource ms = new MediaFileSource(videoFile, "video/quicktime");
newEntry.setMediaSource(ms);
String uploadUrl =
"http://uploads.gdata.youtube.com/feeds/api/users/default/uploads";
VideoEntry createdEntry = service.insert(new URL(uploadUrl), newEntry);
id =createdEntry.getId();
return id;
}
I hope this will save someone else's day.