I need your help:
I have the following method
#Path("/download")
public class FileDownloadService {
#GET
public Response downloadFile(#QueryParam("filenet_id") String filenet_id, #QueryParam("version") String version) {
...
Document document = (Document) cmisObject;
return Response.ok(document, MediaType.APPLICATION_OCTET_STREAM).build();
}
and I want to get the document throught HTTP GET, I tried to write this code but I don't know how to get it, "output" don't conatains it:
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("localhost:8080").setPath("/filenetintegration/rest/download")
.setParameter("filenet_id", filenet_id)
.setParameter("version", version+".0");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
HttpURLConnection urlConnection = (HttpURLConnection) new URL(uri.toString()).openConnection();
urlConnection.connect();
BufferedReader br = new BufferedReader(new InputStreamReader((urlConnection.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
Edit:
maybe the problem is on this line, it don't put the document inside the response:
return Response.ok(document, MediaType.APPLICATION_OCTET_STREAM).build();
You need something like this on the server side:
Document document = (Document) cmisObject;
ContentStream contentStream = document.getContentStream();
final InputStream stream = contentStream.getStream();
StreamingOutput output = (OutputStream out) -> {
try {
int b;
byte[] buffer = new byte[64*1024];
while ((b = stream.read(buffer)) > -1) {
out.write(buffer, 0, b);
}
} finally {
try {
stream.close();
} catch (IOException ioe) {}
}
};
return Response.ok(output, contentStream.getMimeType()).build();
Related
I have a Webservice which give me back this:
{"result":[{"Id":"20","temperatura":"34","humedad":"29","Insertado":"2016-07-01 12:19:42"},{"Id":"21","temperatura":"34","humedad":"29","Insertado":"2016-07-01 12:34:42"},{"Id":"22","temperatura":"35","humedad":"28","Insertado":"2016-07-01 12:49:43"},{"Id":"23","temperatura":"35","humedad":"19","Insertado":"2016-07-01 13:29:06"},{"Id":"24","temperatura":"31","humedad":"18","Insertado":"2016-07-01 13:44:07"},{"Id":"25","temperatura":"33","humedad":"16","Insertado":"2016-07-01 13:59:10"}]}
This is an Object, which has and Array, and the array has many objects.
Here is my code. I am using loopj library-
private void CaptarParametros(String idObjeto) {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put(UtilitiesGlobal.SENSOR_ID, idObjeto);
RequestHandle post = client.post(this, SENSORS_URL, params, new JsonHttpResponseHandler() {
#Override
public void onStart() {
// called before request is started
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// called when response HTTP status is "200 OK"
JSONObject jsonobject = null;
JSONObject dht11JSONbject = null;
JSONArray dht11JSONarray = null;
try {
jsonobject = new JSONObject(String.valueOf(response));
dht11JSONbject = jsonobject.getJSONObject("result");
dht11JSONarray = new JSONArray(dht11JSONbject);
JSONArray dht11 = dht11JSONarray.getJSONArray(0);
for (int i = 0; i < dht11JSONarray.length(); i++) {
JSONObject item = dht11.getJSONObject(i);
String temperatura = item.getString("temperatura");
String humedad = item.getString("temperatura");
//Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + usuarioiJSONbject);
Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + temperatura + humedad);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But I get error like this:
org.json.JSONException: Value [{"Id":"19","temperatura":"35","humedad":"16","Insertado":"2016-07-01 12:19:24"}] at result of type org.json.JSONArray cannot be converted to JSONObject
I would appreciate any help.- I need to extract "temperature" and humedad" in separate arrays since later I have to use it in MPAndroidChat to make tow linechart, one chart for one set of parameters and another one for other parameters.
Solution is here:
try {
jsonobject = new JSONObject(String.valueOf(response));
//dht11JSONbject = jsonobject.getJSONObject("result");
List<String> allNames = new ArrayList<String>();
JSONArray cast = jsonobject.getJSONArray("result");
for (int i=0; i<cast.length(); i++) {
JSONObject parametrosdht11 = cast.getJSONObject(i);
String temperatura = parametrosdht11.getString("temperatura");
String humedad = parametrosdht11.getString("humedad");
allNames.add(temperatura);
allNames.add(humedad);
//Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + usuarioiJSONbject);
Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " +"temperatura: "+ temperatura +" humedad: " +humedad);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
We have a String with many sub_objects, then we have to put them into an array or List.
Take the solution from:
how to parse JSONArray in android
I am facing a problem in value 'return' in Asynctask class in doInBackground method. I am getting an error, about 'missing return statement in below code.
`public class ForecastNetwork extends AsyncTask {
public final String TAG = ForecastNetwork.class.getSimpleName();
#Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(TAG, "Error closing stream", e);
}
}
}
}`
What Should I return at the end?
I assume that you forgot to return the processing result
forecastJsonStr = buffer.toString();
return forecastJsonStr;
I am trying to call a Web API method from a handheld device (Compact Framework) with this code:
// "fullFilePath" is a value such as "\Program Files\Bla\abc.xml"
// "uri" is something like "http://localhost:28642/api/ControllerName/PostArgsAndXMLFile?serialNum=8675309&siteNum=42"
SendXMLFile(fullFilePath, uri, 500);
. . .
public static string SendXMLFile(string xmlFilepath, string uri, int timeout)
{
uri = uri.Replace('\\', '/');
if (!uri.StartsWith("/"))
{
uri = "/" + uri;
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(xmlFilepath))
{
String line;
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());
if (timeout < 0)
{
request.ReadWriteTimeout = timeout;
request.Timeout = timeout;
}
request.ContentLength = postBytes.Length;
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded"; // not "text/xml" correct?
try
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
request.Abort();
return string.Empty;
}
}
}
Somewhere in SendXMLFile(), it is failing with "NotSupportedException" though... As it's running on a handheld device, I can't put a breakpoint in it and step through it; I could sprinkle a bunch of debug statements throughout (MessageBox.Show()), but I'd rather not do that.
The server code never even reaches the breakpoint I put on the "XDocument doc =" line below:
[Route("api/ControllerName/PostArgsAndXMLFile")]
public void PostArgsAndFile([FromBody] string stringifiedXML, string serialNum, string siteNum)
{
XDocument doc = XDocument.Parse(stringifiedXML);
Is it that the Compact framework can't call a (RESTful) Web API method for some reason? Obviously, the client (handheld/Compact Framework) compiles and runs, it just refuses to actually follow through with the runtime realities of it all.
Does my code require a small alteration for it to fit, or do I need to take a completely different tack?
Web API is not going to be able to handle your body content. You declared it as application/x-form-urlencoded, but it is actually XML formatted and your method signature is expecting it to be a XMLDataContract serialized string.
Instead of using the parameter stringifiedXML, instead, just read the body inside your method..
[Route("api/ControllerName/PostArgsAndXMLFile")]
public async void PostArgsAndFile(string serialNum, string siteNum)
{
XDocument doc = XDocument.Parse(await Request.Content.ReadAsStringAsync());
}
Or event better, use a stream directly.
[Route("api/ControllerName/PostArgsAndXMLFile")]
public async void PostArgsAndFile(string serialNum, string siteNum)
{
XDocument doc = XDocument.Load(await Request.Content.ReadAsStreamAsync());
}
This way, you can put the ContentType on the client back to application/xml as it should be.
Using Darrel's code on the server side (I'm using the second one, the Stream), this works on the Client side:
public static string SendXMLFile(string xmlFilepath, string uri, int timeout)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.ContentType = "application/xml";
request.Method = "POST";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(xmlFilepath))
{
String line;
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());
if (timeout < 0)
{
request.ReadWriteTimeout = timeout;
request.Timeout = timeout;
}
request.ContentLength = postBytes.Length;
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded";
try
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
request.Abort();
return string.Empty;
}
}
}
Which can be called like so:
private void buttonNose_Click(object sender, EventArgs e)
{
String fullFilePath = #"C:\McMurtry\LonesomeDove.XML";
String uri = #"http://localhost:21608/api/inventory/sendxml/ff/gg/42";
SendXMLFile(fullFilePath, uri, 500);
}
We are using Google's geolocation API to get the latlong for the wifi access points. We are seeing inconsistent results. Google's API returns different latlong on different boxes. When I test on my development box, I get the latlong which points to a location in US. When I test the same on the amazon ec2 box, I get the latlong which points to a location in Japan. Has anybody else experienced the same with Google's GeoLocation API?
Below is the code and the response strings from both hosts. JDK and JSON jar version is same on both the hosts.
public void testWifiIdMappingApi() {
String apiUrl = "https://www.googleapis.com/geolocation/v1/geolocate?key=xxxxxxxxxxxxxxxxxxxxxxxx";
InputStream inputStream = null;
HttpsURLConnection con = null;
DataOutputStream wr = null;
try {
URL url = new URL(apiUrl);
con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
JSONObject obj = new JSONObject();
JSONArray wifiAry = new JSONArray();
JSONObject wifiObj = new JSONObject();
wifiObj.put("macAddress", "6c:f3:7f:4b:37:74");
wifiObj.put("signalStrength", 60);
wifiAry.add(wifiObj);
wifiObj = new JSONObject();
wifiObj.put("macAddress", "6c:f3:7f:4b:37:75");
wifiObj.put("signalStrength", 60);
wifiAry.add(wifiObj);
obj.put("wifiAccessPoints", wifiAry);
System.out.println(obj.toString());
wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(obj.toString());
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
inputStream = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
inputStream = con.getInputStream();
} else {
inputStream = con.getErrorStream();
}
final char[] buffer = new char[4096];
StringBuilder response = new StringBuilder();
Reader r = new InputStreamReader(inputStream, "UTF-8");
int read;
do {
read = r.read(buffer, 0, buffer.length);
if (read > 0) {
response.append(buffer, 0, read);
}
} while (read >= 0);
System.out.println(new java.util.Date() + " - "
+ response.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null)
inputStream.close();
if (wr != null)
wr.close();
if (con != null)
con.disconnect();
} catch (Exception e) {
}
}
}
Input JSON String
{"wifiAccessPoints":[{"signalStrength":60,"macAddress":"6c:f3:7f:4b:37:74"},
{"signalStrength":60,"macAddress":"6c:f3:7f:4b:37:75"}]}
Response on the amazon ec2 host
{
"location": {
"lat": 40.603124,
"lng": 140.463922
},
"accuracy": 122000.0
}
Response on my development box (windows 7)
{
"location": {
"lat": 37.593392,
"lng": -122.04383
},
"accuracy": 22000.0
}
You might want to pass the considerIp field as False in your POST body. This would be what Google determines to be your location when the wifi routers aren't doing their job.
I want to upload an image in blackberry simulator using MultipartPostData, the following is my code but it does not seem to work. I have also signed my .cod file. Can anyone help me please?
public void postData(String Url, bytes[] data)
{
if (DeviceInfo.isSimulator()){
Url=Url+";deviceSide=true";
}
HttpConnection httpConn=null;
OutputStream os=null;
InputStream is=null;
String url=Url;
try {
PostData form = new MultipartPostData(MultipartPostData.DEFAULT_CHARSET, false) ;
byte [] postData = data;
form.setData(postData);
httpConn = (HttpConnection) Connector.open(url);
httpConn.setRequestMethod(HttpConnection.POST);
httpConn.setRequestProperty("User-Agent", "BlackBerry");
httpConn.setRequestProperty("Content-Type", "multipart/form-data");
httpConn.setRequestProperty("MIME-Type", "Image/Jpeg");
httpConn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, String.valueOf(postData.length));
httpConn.setRequestProperty("Content-Language", "en-US");
os =httpConn.openOutputStream();
os.write(form.getBytes());
//read response
StringBuffer sb = new StringBuffer();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1)
sb.append((char) chr);
System.out.println("Result................................ " + sb.toString());
String result=sb.toString();
}
catch(Exception e)
{
System.out.println(e.toString());
}
finally {
try{
if(is!= null)
is.close();
if(os != null)
os.close();
if(httpConn != null)
httpConn.close();
} catch(Exception e1){
System.out.println(e1.toString());
}
}
}
//you must have a bundary format post data, the .cod file must be work on the simulator
httpConn = (HttpConnection)connDesc.getConnection();
httpConn.setRequestMethod(HttpConnection.POST);
httpConn.setRequestProperty("user-agent", "BlackBerry");
httpConn.setRequestProperty("content-type", "multipart/form-data; boundary=----------V2ymHFg03ehbqgZCaKO6jy");
os = httpConn.openOutputStream();
//os.write(form.getBytes());
byte[] fileBytes = {1,2,3,4}; //retrieve file bytes with your own code
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(("\r\n--" + "----------V2ymHFg03ehbqgZCaKO6jy" + "\r\n").getBytes());
bos.write(("Content-Disposition: form-data; name=\"mifoto\"; filename=\"leo.gif\"\r\n").getBytes());
bos.write(("Content-Type: image/gif\r\n\r\n").getBytes());
bos.write(fileBytes);
bos.write(("\r\n--" + "----------V2ymHFg03ehbqgZCaKO6jy" + "--\r\n").getBytes());
os.write(bos.toByteArray());
As soon as you call MultipartPostData.setData(), it overwrites any Content-Disposition data you have set with MultipartPostData.append().
leonel's answer works or you can use Vlad Patryshev's ClientHttpRequest class.