I need to send a body for a POST JSON to a REST service for Blackberry java OS6+. I have seen examples, but not how to create such a body. Then, I need to send the body created earlier in a POST?
An example of the body that I need to send is this:
Body:
{
"name" : "my name",
"password" : "asdf",
"email" : "mail#mail.com",
"gender" : 0,
}
And the service will return:
{
"response": {
"status": "ok"
}
}
THIS IS THE SOLUTION
Only had to change the String to JSONObject body.
Solamente tenia que cambiar el cuerpo String a JSONObject.
String url = "http://example.json";
String result;
String tipoConexion = Autenticacion.getConnectionString();
public Consumo4()
{
try{
JSONObject json = new JSONObject (
"{"+
"'name' : 'test',"+
"'email' : 'test#test.com',"+
"'password' : 'password',"+
"'gender' : 0,"+
"}"
);
HttpConnection connection = (HttpConnection)Connector.open(url+tipoConexion);
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Length", Integer.toString(json.length()));
System.out.println("JSON A ENVIAR --> " + json);
String size = "" + json.length();
OutputStream os = connection.openOutputStream();
os.write(json.toString().getBytes("UTF-8"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream responseData = connection.openInputStream();
byte[] buffer = new byte[20000];
int bytesRead = responseData.read(buffer);
while(bytesRead > 0) {
baos.write(buffer, 0, bytesRead);
bytesRead = responseData.read(buffer);
}
baos.close();
connection.close();
result = new String(baos.toByteArray(), "UTF-8");
System.out.println("JSON RECIBIDO --> " + result);
} catch (IOException ex) {
//screen.requestFailed(ex.toString());
System.out.println("FALLĂ“:: " + ex);
} catch (Exception e) {
e.printStackTrace();
}
}
Related
According to the dojo tutorial and several examples here, I am trying to send multiple multiple file help. The files to the servlet will arrive in the directory, but the dojo will return the exception
I use dojo 1.10 and javax.servlet.http.HttpServlet v3.0.1
PrintWriter out = response.getWriter();
try {
if (ServletFileUpload.isMultipartContent(request)) {
try {
#SuppressWarnings("unchecked")
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File("/tmp/eshop/" + File.separator + name));
}
}
out.print("[{uploadresult:'Upload is ok!'}]");
} catch (Exception ex) {
out.print("{uploadresult: 'File upload failed due to : '" + ex+"}");
}
} else {
out.print("{uploadresult:'Sorry this servlet only handles file upload request.'}");
}
out.close();
} catch (Exception e) {
logger.error(e);
}
Error thrown :
/dojo/v1.10/dojox/form/uploader/_HTML5.js:80 Error parsing server
result: SyntaxError: Unexpected token u in JSON at position 2
at JSON.parse ()
at Object.eval (/dojo/v1.10/dojox/form/uploader/_HTML5.js:76)
at XMLHttpRequest. (dojo.js: 15) (anonymous) # /dojo/v1.10/dojox/form/uploader/_HTML5.js:80
/dojo/v1.10/dojox/form/uploader/_HTML5.js:81 [{uploadresult: 'Upload
is ok!'}]
First of all , set the response to json format
add first the response.setContentType("application/json");
And you thing you've to format the json correctly by adding quotes to the key like :
response.setContentType("application/json");
PrintWriter out = response.getWriter();
try {
if (ServletFileUpload.isMultipartContent(request)) {
try {
#SuppressWarnings("unchecked")
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File("/tmp/eshop/" + File.separator + name));
}
}
out.print("[{'uploadresult':'Upload is ok!'}]");
} catch (Exception ex) {
out.print("{'uploadresult': 'File upload failed due to : '" + ex+"}");
}
} else {
out.print("{'uploadresult':'Sorry this servlet only handles file upload request.'}");
}
out.close();
} catch (Exception e) {
logger.error(e);
}
I've been trying without success today to adapt this example to POST data instead of the example GET that is provided.
http://blogs.msdn.com/b/andy_wigley/archive/2013/02/07/async-and-await-for-http-networking-on-windows-phone.aspx
I've replaced the line:
request.Method = HttpMethod.Get;
With
request.Method = HttpMethod.Post;
But can find no Method that will allow me to stream in the content I wish to POST.
This HttpWebRequest seems a lot cleaner than other ways e.g. sending delegate functions to handle the response.
In Mr Wigley's example code I can see POST so it must be possible
public static class HttpMethod
{
public static string Head { get { return "HEAD"; } }
public static string Post { get { return "POST"; } }
I wrote this class some time ago
public class JsonSend<I, O>
{
bool _parseOutput;
bool _throwExceptionOnFailure;
public JsonSend()
: this(true,true)
{
}
public JsonSend(bool parseOutput, bool throwExceptionOnFailure)
{
_parseOutput = parseOutput;
_throwExceptionOnFailure = throwExceptionOnFailure;
}
public async Task<O> DoPostRequest(string url, I input)
{
var client = new HttpClient();
CultureInfo ci = new CultureInfo(Windows.System.UserProfile.GlobalizationPreferences.Languages[0]);
client.DefaultRequestHeaders.Add("Accept-Language", ci.TwoLetterISOLanguageName);
var uri = new Uri(string.Format(
url,
"action",
"post",
DateTime.Now.Ticks
));
string serialized = JsonConvert.SerializeObject(input);
StringContent stringContent = new StringContent(
serialized,
Encoding.UTF8,
"application/json");
var response = client.PostAsync(uri, stringContent);
HttpResponseMessage x = await response;
HttpContent requestContent = x.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
if (x.IsSuccessStatusCode == false && _throwExceptionOnFailure)
{
throw new Exception(url + " with POST ends with status code " + x.StatusCode + " and content " + jsonContent);
}
if (_parseOutput == false){
return default(O);
}
return JsonConvert.DeserializeObject<O>(jsonContent);
}
public async Task<O> DoPutRequest(string url, I input)
{
var client = new HttpClient();
CultureInfo ci = new CultureInfo(Windows.System.UserProfile.GlobalizationPreferences.Languages[0]);
client.DefaultRequestHeaders.Add("Accept-Language", ci.TwoLetterISOLanguageName);
var uri = new Uri(string.Format(
url,
"action",
"put",
DateTime.Now.Ticks
));
string serializedObject = JsonConvert.SerializeObject(input);
var response = client.PutAsync(uri,
new StringContent(
serializedObject,
Encoding.UTF8,
"application/json"));
HttpResponseMessage x = await response;
HttpContent requestContent = x.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
if (x.IsSuccessStatusCode == false && _throwExceptionOnFailure)
{
throw new Exception(url + " with PUT ends with status code " + x.StatusCode + " and content " + jsonContent);
}
if (_parseOutput == false){
return default(O);
}
return JsonConvert.DeserializeObject<O>(jsonContent);
}
}
Then when I want to call it, I can use it as following :
JsonSend<User, RegistrationReceived> register = new JsonSend<User, RegistrationReceived>();
RegistrationReceived responseUser = await register.DoPostRequest("http://myurl", user);
I am facing problem in saving data on google map engine data source. Error : buffer length is greater than 1 : { "error": { "errors": [ { "domain": "global", "reason": "invalid", "message": "This value is invalid." } ], "code": 400, "message": "This value is invalid." }}
where "buffer length is greater than 1 " is a custom message.
Feature :
{"features":[{"properties":{"Name":"Vijay Tr","Work_Email":"vijay.tomar#lovly.com","Job_Title":"Lead r","Reporting_Location":"Ind ","Total_Experience":9,"Mobile_Phone":"9313432451","Department":"LINT","gx_id":"","Reporting_To":"Ashish Gupta"},"type":"Feature","geometry":{"type":"Point","coordinates":[77.02190399169922,28.455472946166992]}}]}
Feature is a Valid Json.
try {
mapDataURL = new URL(url);
if (mapDataURL != null) {
urlConnection = mapDataURL.openConnection();
urlConnection.setConnectTimeout(600000);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type","application/json");
String gmeToken = saa.getOAuthTokenForMapsEngine();
if (gmeToken != null && gmeToken.length() > 0) {
urlConnection.setRequestProperty("Authorization", "Bearer " + gmeToken);
}
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
JSONArray latLngAry = new JSONArray();
latLngAry.put(Float.parseFloat(lng));
latLngAry.put(Float.parseFloat(lat));
JSONObject geometry=new JSONObject();
geometry.put("type","Point");
geometry.put("coordinates",latLngAry);
JSONObject jsonProperties=new JSONObject();
jsonProperties.put("Name",name.trim());
jsonProperties.put("Job_Title",jobTitle.trim());
jsonProperties.put("Reporting_To",reportingTo.trim());
jsonProperties.put("Department",department.trim());
jsonProperties.put("Work_Email",email.trim());
jsonProperties.put("Mobile_Phone",mobilePhone.trim());
jsonProperties.put("Reporting_Location",reportingLocation.trim());
jsonProperties.put("Total_Experience",Float.parseFloat(experience.trim()));
jsonProperties.put("gx_id", "" + gx_id + "");
JSONObject jsonFeature=new JSONObject();
jsonFeature.put("properties", jsonProperties);
jsonFeature.put("type", "Feature");
jsonFeature.put("geometry", geometry);
String jsonStr = "{\"features\":[" + jsonFeature + "]}";
log.info("jsonStr : "+jsonStr);
wr.write(jsonStr);
log.info(" writing String Success : "+wr.toString());
wr.flush();
log.info("Url : "+mapDataURL);
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
buffer.append(line);
}
wr.close();
rd.close();
}
} catch (MalformedURLException e) {
buffer = new StringBuffer("MalformedURLException : "+ e.getMessage() );
} catch (IOException e) {
buffer = new StringBuffer("IOException : " +e.getMessage());
} catch (Exception e) {
buffer = new StringBuffer("Generic Exception : "+e.getMessage());
} finally {
if (buffer.length() < 1) {
return true;
} else {
log.info("buffer length is greater than 1 : "+buffer.toString());
return false;
}
}
Did you intend to return true here? With buffer.length() < 1, any value that is greater than an empty buffer will cause it to return false. So, if buffer.append(line) is expected to be called, you will always return false.
I suggest changing the buffer.length() < 1 condition.
I'm new to windows phone 8 development.
Could you please help me how to send the xml data to the server through http post calls in windows phone 8?
Thanks
This is a sample code I used in my project. Modify according to your needs
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("url to submit to");
req.Method = "POST";
//Add a Header something like this
//req.Headers["SOAPAction"] = "http://asp.net/ApplicationServices/v200/AuthenticationService/Login";
req.ContentType = "text/xml; charset=utf-8";
//req.UserAgent = "PHP-SOAP/5.2.6";
string xmlData = #"<?xml version=""1.0"" encoding=""UTF-8""?>Your xml data";
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(xmlData);
req.Headers[HttpRequestHeader.ContentLength] = byteArray.Length.ToString();
req.BeginGetRequestStream(ar =>
{
using (var requestStream = req.EndGetRequestStream(ar))
{
// Write the body of your request here
requestStream.Write(byteArray, 0, xmlData.Length);
}
req.BeginGetResponse(a =>
{
try
{
var response = req.EndGetResponse(a);
var responseStream = response.GetResponseStream();
using (var streamRead = new StreamReader(responseStream))
{
// Parse the response message here
string responseString = streamRead.ReadToEnd();
//If response is also XML document, parse it like this
XDocument xdoc = XDocument.Parse(responseString);
string result = xdoc.Root.Value;
if (result == "true")
{
//Do something here
}
else
Dispatcher.BeginInvoke(() =>
{
//result failed
MessageBox.Show("Some error msg");
});
}
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(() =>
{
//if any unexpected exception occurs, show the exception message
MessageBox.Show(ex.Message);
});
}
}, null);
}, null);
The following code returns bad request exception.Not sure what's wrong here .
string appId = "956vaQc49TdepGpsywiM+BRqfxfgOTeCr/514=";
//go to http://msdn.microsoft.com/en-us/library/ff512386.aspx to obtain AppId.
string text = "translate this";
string language = "en";
System.Uri uri = new Uri("http://api.microsofttranslator.com/v2/Http.svc/Speak?&appId=" + appId + "&text=" + text + "&language=" + language);
try
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(uri);
response.EnsureSuccessStatusCode();
Stream responseBody = await response.Content.ReadAsStreamAsync();
// meTextToSpeeach.Source = uri;
string strResponse;
using (Stream responseStream = responseBody)
{
using (StreamReader sr = new StreamReader(responseStream, System.Text.Encoding.Unicode))
{
strResponse = sr.ReadToEnd();
}
}
}
catch (Exception)
{
}
You are not encoding the parameters (appId, text, language). You should be doing "..." + WebUtility.UrlEncode(appId) + "..." ...