badrequest error while requesting bing microsofttranslate api? - windows-runtime

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) + "..." ...

Related

Printing ArrayList values in SpringBoot

I created an ArrayList with the json values from an Rest API.
This is the code to read the Rest API:
#RestController
public class exemploclass {
#RequestMapping(value="/vectors")
//#Scheduled(fixedRate = 5000)
public ArrayList<StateVector> getStateVectors() throws Exception {
ArrayList<StateVector> vectors = new ArrayList<>();
String url = "https://opensky-network.org/api/states/all?lamin=41.1&lomin=6.1&lamax=43.1&lomax=8.1";
//String url = "https://opensky-network.org/api/states/all?lamin=45.8389&lomin=5.9962&lamax=47.8229&lomax=10.5226";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject myResponse = new JSONObject(response.toString());
JSONArray states = myResponse.getJSONArray("states");
System.out.println("result after Reading JSON Response");
for (int i = 0; i < states.length(); i++) {
JSONArray jsonVector = states.getJSONArray(i);
String icao24 = jsonVector.optString(0);
String callsign = jsonVector.optString(1);
String origin_country = jsonVector.optString(2);
Boolean on_ground = jsonVector.optBoolean(8);
//System.out.println("icao24: " + icao24 + "| callsign: " + callsign + "| origin_country: " + origin_country + "| on_ground: " + on_ground);
//System.out.println("\n");
StateVector sv = new StateVector(icao24, callsign, origin_country, on_ground);
vectors.add(sv);
}
System.out.println("Size of data: " + vectors.size());
return vectors;
}
}
The last line " return vectors;" returns a list with the values i parsed and returns it like this:
But i want this more "pretty", i want it to be one Array in each line, how can i achieve this?
P.S. Its on the .html page, not on console
Your return value seems a valid Json Object. If you want it more pretty so you can read it clearly then pass it through an application that makes that json pretty.
If you call your API from Postman, it will give you a pretty Json Object which will be better formatted. This will be because you have annotated your controller with #RestController so it will deliver an application/json response which Postman will know and then it will try to make it prettier.
P.S. Its on the .html page, not on console
So you hit your API from a browser. Most browsers don't expect a Json object to be returned, so they will not make it pretty. You can't force that from your Service either.
Just hit your API from Postman, it will understand it and make it pretty.

In Unity, using UnityWebRequest, I cant print the body of the object I want

I used to do a post request using native C#'s library
var httpWebRequest = (HttpWebRequest)WebRequest.Create(djangoApi + user);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"wallet_id\":\""+wallet+"\"," +
"\"token\":\"foo\"}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
but that doesn't work on mobile. So, I need to use UnityWebRequest
Following the example, https://docs.unity3d.com/Manual/UnityWebRequest-SendingForm.html, my functions look almost identical. Here is the coroutine function
IEnumerator SendPostCoroutine()
{
WWWForm form = new WWWForm();
form.AddField("user_id", "0x241477cE189fa014292d99e0807cB449b878");
form.AddField("token", "foo");
using (UnityWebRequest www = UnityWebRequest.Post(djangoApi + user, form))
{
Debug.Log(www.downloadHandler.text);
yield return www.SendWebRequest();
if (www.isNetworkError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("POST successful!");
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> dict in www.GetResponseHeaders())
{
sb.Append(dict.Key).Append(": \t[").Append(dict.Value).Append("]\n");
}
// Print Headers
Debug.Log(sb.ToString());
string response = Encoding.UTF8.GetString(www.downloadHandler.data);
Debug.Log(response);
Debug.Log(www.downloadHandler.text);
}
}
}
When I do
string response = Encoding.UTF8.GetString(www.downloadHandler.data);
Debug.Log(response);
Debug.Log(www.downloadHandler.text);
neither prints out the body of the object I want. Instead, all I get is
<!DOCTYPE html>
<html lang="en">
What can I do to get the values within the json?
I just used
IEnumerator Post(string url, string bodyJsonString)
{
var request = new UnityWebRequest(url, "POST");
byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.Send();
Debug.Log("Status Code: " + request.responseCode);
}
taken from https://forum.unity.com/threads/posting-json-through-unitywebrequest.476254/. That way, I can post my raw json

POST data to web service HttpWebRequest Windows Phone 8

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);

Http post call in windows phone 8

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);

How do I send API push message with .Net / Parse.com? (C#)

This is my application code for sending push message using PARSE
public static string ParseAuthenticate(string strUserName, string
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.parse.com/1/push");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("X-Parse-Application-Id", "my app id");
httpWebRequest.Headers.Add("X-Parse-REST-API-KEY", "my rest api key");
httpWebRequest.Method = "POST";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
return responseText;
}
}
Request body
{
"channels": [
"test"
],
"data": {
"alert": "12345"
}
}
Above code where is pass my request parameter(body)? how to frame my request as JSON format?
Thanks in advance.Please help me to solve this issue.
Bellow code is running for push notification using parse in .net.
private bool PushNotification(string pushMessage)
{
bool isPushMessageSend = false;
string postString = "";
string urlpath = "https://api.parse.com/1/push";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlpath);
postString = "{ \"channels\": [ \"Trials\" ], " +
"\"data\" : {\"alert\":\"" + pushMessage + "\"}" +
"}";
httpWebRequest.ContentType = "application/json";
httpWebRequest.ContentLength = postString.Length;
httpWebRequest.Headers.Add("X-Parse-Application-Id", "My Parse App Id");
httpWebRequest.Headers.Add("X-Parse-REST-API-KEY", "My Rest API Key");
httpWebRequest.Method = "POST";
StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
requestWriter.Write(postString);
requestWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
JObject jObjRes = JObject.Parse(responseText);
if (Convert.ToString(jObjRes).IndexOf("true") != -1)
{
isPushMessageSend = true;
}
}
return isPushMessageSend;
}
To send Notification to all app user you have to set the
Data field like so:
postString = "{\"data\": { \"alert\": \"Test Notification 2 From Parse Via Chinwag Admin\" },\"where\": { \"deviceType\": \"ios\" }}";