i wanna send image along with text from my android client to wcf web service on localhost. i have successfully sent text and received as well and as it was quite difficult for me just to send text but now i have to send image along with text as well. i'd prefer not to change my method like using stream etc. i want to pass image as json and receive it in my web service and store it in sql database image column or even storing on disc would do. So please tell me what changes i need to make in code below to do it.
Thanks in advance...!
here's my AddIssue method of web service.
public int AddIssue(Issue issue)
{
// byte[] bm=System.Convert.FromBase64String(issue.Image.ToString());
//Binary bo = new Binary(bm);
try
{
NorthwindDataContext dc = new NorthwindDataContext();
Issue currentIssue = new Issue
{
Area = issue.Area,
Description= issue.Description,
// Image =bo
};
if (currentIssue == null)
{
// Couldn't find an [Order] record with this ID
return -3;
}
dc.Issues.InsertOnSubmit(currentIssue);
// Update our SQL Server [Order] record, with our new Shipping Details (send from whatever
// app is calling this web service)
dc.SubmitChanges();
return 0; // Success !
}
catch (Exception)
{
return -1;
}
}
and here's my java code. i have tried different codes but none worked. the above two codes work with a C# client but i need it in java i.e android.
JSONObject json = new JSONObject();
json.put("Area",editTextPrice.getText().toString());
json.put("Description",editTextDescription.getText().toString());
img.buildDrawingCache();
Bitmap bm=img.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b , Base64.DEFAULT);
json.put("Image",encodedImage);
issue class of my web service
namespace JSONWebService
{
[DataContract]
[Serializable]
public class wsIssue
{
[DataMember]
public int IssueId { get; set; }
[DataMember]
public string Area { get; set; }
[DataMember]
public string Description { get; set; }
[DataMember]
public string Image { get; set; }
}
n here's interface of my web service
namespace JSONWebService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "getAllIssues")]
List<wsIssue> GetAllIssues();
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json,RequestFormat = WebMessageFormat.Json, UriTemplate = "AddIssue")]
int AddIssue(Issue issue);
i have tried directly using json.toString() instead of byte but that didn't work either.
I don't know what error you get from android side but you can also try with HttpUrlConnection to send data check this answer.
Or look this answer if you want to use HttpPost:
https://stackoverflow.com/questions/6360207/android-sending-a-byte-array-via-http-post
JSONObject args = new JSONObject();
args.put("Area", editTextPrice.getText().toString());
args.put("Description", editTextDescription.getText().toString())
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b , Base64.DEFAULT);
args.put("image",encodedImage);
//You can also use NameValuePair instead JSON
//like : nameValuePairs.add(new BasicNameValuePair("Area", editTextPrice.getText().toString());
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("data", arg.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
On C# get image string then change to bytearray
public class Message
{
public string Area {get;set;}
public string Description {get;set;}
public string Image {get;set;}
}
Message message = new JavaScriptSerializer().Deserialize<Message>(result);
byte[] imageData = Convert.FromBase64String(message.image);
MemoryStream ms = new MemoryStream(imageData);
Image returnImage = Image.FromStream(ms);
Related
I have a Java Spring Boot web service and I am trying to send push notifications to an iOS device.
The problem I am facing is that the emoji text Which is directly pasted, like
String emoji = "😀";
Or its code, like
String emoji = "\uD83D\uDE0A";
it shows as ? (Question mark symbol)
I have tried getting it as bytes of UTF_8 characters like this:
byte[] emojis = user.getEmoji().getBytes(); //Here user.getEmoji() returns a collection of 2-3 emojis
String emojisAsString = new String(emojis, StandardCharsets.UTF_8);
Integer emojiCodePoint = emojisAsString.codePointAt(emojisAsString.offsetByCodePoints(0,0));
char emojiChars[] = {Character.highSurrogate(emojiCodePoint), Character.lowSurrogate(emojiCodePoint)};
But it still shows as question marks.
I also tried using UTF-8 code like "\xE2\x9A\xA1" but this one just got printed as it is on the notification.
Also when I call the notification API from postman using FCM APIs and paste emojis, it shows emojis in the notification, it just shows as question marks when done through Java web service.
This is the Push notification service code
#RequestMapping(value = "/send", method = RequestMethod.GET, produces = "application/json")
public static ResponseEntity<String> send(String message, String deviceToken, Integer type, Object response, String userNameAsTitle) {
//response.setMessage(message);
//response.setNotificationType(type);
JSONObject body = new JSONObject();
body.put("to", deviceToken);
body.put("priority", "high");
Map<String, Object> map = new HashMap<>();
map.put("title", userNameAsTitle);
map.put("body", message);
//map.put("alert", descprtion);
map.put("type", type);
map.put("badge", 1);
map.put("sound", "default");
map.put("response", response);
JSONObject notification = new JSONObject(map);
//body.put("notification", notification);
body.put("notification", notification);
HttpEntity<String> request = new HttpEntity<>(body.toString());
CompletableFuture<String> pushNotification = androidPushNotificationsService.send(request);
CompletableFuture.allOf(pushNotification).join();
try {
String firebaseResponse = pushNotification.get();
System.out.println(firebaseResponse.toString());
return new ResponseEntity<>(firebaseResponse.toString(), HttpStatus.OK);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return new ResponseEntity<>("Push Notification ERROR!", HttpStatus.BAD_REQUEST);
}
Hey so I'm trying to send some json-object to a rest web service, then get the value of some specific keys, then process the data to finally return a new json-object which is going to be used in another place. Anyway, I'm getting HTTP 204 when I try to communicate with the service.
My rest service looks like this
#Path("/example")
public class PdfMaker {
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response PruebasMet(JSONObject json) throws IOException, JSONException{
try{
String xml = json.getString("xml");
String plantilla = json.getString("plant");
//method that uses "xml" and "plant" and returns "pdf"
JSONObject response = new JSONObject();
response.put("pdf", pdf);
return Response.status(200).entity(pdfb64.toString()).build();
}catch(Exception e){
e.getStackTrace();
return null;
}
}
and I'm trying to communicate with this
public class Jersey {
public static String baseuri = "http://localhost:8080/PdfMakerGF/rest/example/post";
public static void main(String[] args) {
try {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource webResource = client.resource(baseuri);
JSONObject objTest = new JSONobject();
objTest.put("xml","Data1");
objTest.put("plan", "Data2");
ClientResponse res = webResource.header("Content-Type","application/json;charset=UTF-8")
.post(ClientResponse.class, objTest.toString());
System.out.println("output..." + "\n");
System.out.println("Answer "+res);
} catch (Exception e) {
e.printStackTrace();
}
}
But the response that I receive is this one
Answer POST http://localhost:8080/PdfMakerGF/rest/example/post
returned a response status of 204 No Content
Obviously there is something wrong but can't see what is it.
Since I'm stuck with this. Any kind of help would be appreciated.
I'm using netbeans 8.1, Glassfish 4.1 and Jersey.
Thanks
If your server runs into an exception and goes to the catch block, it returns null which corresponds to HTTP 204 (No Content). As sisyphus commented, there should be some exception in the server standard output.
So you probably need to:
Return a different response code (e.g. INTERNAL_SERVER_ERROR or
BAD_REQUEST) in the catch block
Check why the server code is throwing
the exception
Most likely you get an Exception. I guess it is because you have "plant" in one place and "plan" in another.
okey so finaly it works what i need to change was the way that the service was reciving the data, with a inner class in my case, end up working like this ..
Class Aux{
String xml;
String plant;
//generate gettes and setters :)
}
#Path("/example")
public class PdfMaker {
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response PruebasMet(Aux json) throws IOException,
JSONException{
try{
String xml = json.getXml();
String plant = json.getPlant();
//method that uses "xml" and "plant" and returns "pdf"
JSONObject response = new JSONObject();
response.put("pdf", pdf);
return Response.status(200).entity(pdf)).build();
}catch(Exception e){
e.getStackTrace();
return null;
}
}
and the client is ..
Client client = new Client();
WebResource wresource = client.resource("http://localhost:8080/PdfMakerGF/rest/example/post");
JSONObject json = new JSONObject();
json.put("xml", DATA);
json.put("plant", DATA);
ClientResponse response =
wresource.type("application/json").post(ClientResponse.class,
json.toString());
out = response.getEntity(String.class);
System.out.println("RES = "+response);
System.out.println("OUT = "+out);
out has the info that the service is Providing
I have a weird question. I am working on a Java project for work, where we need to make HTTP GET/POST calls to our WEB API. I wanted to make a WebAPI testing project in C#; run it locally (localhost on some random port) and make sure I am sending the right stuff. That way I could control what was sent back(success, errors, JSON, XML, and different variables like that).
Here is some key stuff I have so far:
Client-Java code:
public String sendAPIRequest( HttpRequestMethod method, String apiURI, String payload) throws IOException
{
// Method is GET, POST....
// apiURL specific API navigating to.
// pauload is the html body.
if(payload == null)
{
payload = "";
}
// Establish a connection.
String strURL = String.format("%s%s", this.BaseURL, apiURI);
URL url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("Accept-Charset", this.CHARSET);
conn.setRequestMethod(method.toString());
conn.setRequestProperty("Content-Type", "text/json;charset=" + this.CHARSET);
conn.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
conn.setRequestProperty("Accept","*/*");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
// write the payload out, if it exists.
//if(payload != null)
{
try(OutputStream output = conn.getOutputStream())
{
output.write(payload.getBytes(CHARSET));
}
}
// read the response.
StringBuilder response = new StringBuilder();
InputStream input = conn.getInputStream();
try(Scanner inputScanner = new Scanner(input))
{
while(inputScanner.hasNextLine())
{
response.append((inputScanner));
}
}
return response.toString();
}
public String CheckForApplicableLicenses(String dCode, String key)
{
String result;
try
{
String APICall = String.format("/license/find_matching?d_code=%s&key=%s", dCode, key);
String Response = API.sendAPIRequest(HttpRequestMethod.GET, APICall);
// TODO Parse the String Response JSON/XMl.
result = Response;
}
catch(Exception ex)
{
// TODO: incorporate some sort of logging and error handling.
result = ex.toString();
}
return result;
}
Server-C#.Net code (tested with fiddler, and in the browser):
[Route("api/[controller]")]
public class LicenseController : Controller
{
[HttpGet]
[Route("find_matching")]
public IEnumerable<string> find_matching(string d_code = "", string key = "")
{
return new string[] { d_code, key };
}
}
Results so far:
I've gotten 404 errors, and I have been able to connect. Most of the time the Java client blows up when I get to the creating the InputStream. I've never been able to trip the breakpoint in the C# server.
Questions:
1) Is what I am doing even feasible? I'm really just trying to test the Java Client, without calling the API, before I am ready. Maybe it has something to do with not running the service on the default HTTP port of 80?
2) Is there a better way of testing this? I don't want to make call to our actual service until we are done.
Thanks in advance for an assistance.
I have an application that works on Java and AngularJS.
I create pdf files with Java, using FileOutputStream to store them:
#RequestMapping(value = "/getPdf",
method = RequestMethod.GET)
#RolesAllowed(AuthoritiesConstants.USER)
public List<String> getPdf(#RequestParam(value = "id") Long id){
FileOutputStream fileStream = null;
String fileName = textRepository.findOne(id).getTitle() + ".pdf";
String text = textRepository.findOne(id).getUserText();
try {
fileStream = new FileOutputStream(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// create an API client instance
Client client = new Client("", "");
client.convertHtml(text, fileName);
try {
fileStream.close();
} catch (IOException e) {
e.printStackTrace();
}
List<String> out = new ArrayList<>();
out.add(fileName);
return out;
}
They are created in the root directory of my application.
Now I want to implement a functionality that lets the user to download a pdf by clicking on a link or a button. I have tried with $window.open(), but I can't manage to get the path to my pdf file.
$scope.getPdf = function (id) {
TextService.getPdf(id).success(function(data){
$window.open('../../../../../../' + data[0], '_blank', 'download');
});
};
Here i get an error saying that Cannot GET /data.pdf
EDIT - solved the problem
I had to do a POST method that sends the file:
#RequestMapping(value = "/getPdf",
method = RequestMethod.POST)
#RolesAllowed(AuthoritiesConstants.USER)
public ResponseEntity<byte[]> getPdf(#RequestBody Long id){
String filename = textRepository.findOne(id).getTitle() + ".pdf";
String text = textRepository.findOne(id).getUserText();
ByteArrayOutputStream pdf = new ByteArrayOutputStream();
// create an API client instance
Client client = new Client("", "");
client.convertHtml(text, pdf);
byte[] content = pdf.toByteArray();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
headers.setContentDispositionFormData("inline", filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(content, headers, HttpStatus.OK);
return response;
}
and back to my AngularJS client i have a service that calls the Java method:
angular.module("eddieApp")
.factory("TextService", function($http){
return{
getPdf: function(id){
return $http.post('texts/getPdf', id, { responseType: 'arraybuffer' });
}
};
});
Now in the controller all i had to do is call the service and open a window with the pdf:
$scope.getPdf = function (id) {
TextService.getPdf(id).success(function(data){
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = ($window.URL || $window.webkitURL).createObjectURL(file);
$window.open(fileURL, '_blank', 'download');
});
};
Hope it helps someone!
If you are serving the angular portion from a webserver, you cannot access the filesystem of the server. That would be a severe security problem.
Why not provide another #RequestMapping(value = "/getFile") which serves the file directly to the user, using the proper MIME type as well?
Here is a similar question Return generated pdf using spring MVC with an answer on how to do that.
i hope to help. I think the problem is in the window.open, first should exist a service that makes a post with the url, call the service will pass the id and now if you make the window.open
I am porting an app from BB10 to android. For an http request I am using AQuery.
In Qt on BB10, I can simply post data:
QByteArray data = "test";
QNetworkRequest request;
request.setUrl(new QUrl("example.com"));
QNetworkAccessManager manager = new QNetworkAccessManager(this);
manager->post(request,data);
but in AQuery I can only find a POST method with key/value pairs (from the doc):
String url = "http://search.twitter.com/search.json";
Map<String, Object> params = new HashMap<String, Object>();
params.put("q", "androidquery");
aq.ajax(url, params, JSONObject.class, new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject json, AjaxStatus status) {
showResult(json);
}
});
Is there a way to POST just data in AQuery?
I have found out how to do this.
In the AQuery source, in the httpEntity method of the AbstractAjaxCallback class:
HttpEntity entity = null;
Object value = params.get(AQuery.POST_ENTITY);
if(value instanceof HttpEntity){
entity = (HttpEntity) value;
} else {
//urlencoded POST data
}
So all I needed to do was this:
HttpEntity entity = new StringEntity(data);
cb.param(AQuery.POST_ENTITY,entity);
where cb is my AjaxCallback object.