Sending String[] Array over J2ME Socket Connection using ObjectOuputStream - sockets

I am trying to send a String[] array in j2me using ObjectOUputStream, but i keep getting this error,
java.lang.IllegalArgumentException: Not an HTTP URL
Here is my code:
OutputStream os=null;
HttpConnection hc= null;
ObjectOutputStream oj=null;
//get the URL
String serverURL=entry.getUrl();
hc=(HttpConnection)Connector.open(serverURL, Connector.READ_WRITE, true);
hc=(HttpConnection)Connector.open(serverURL);
hc.setRequestMethod (HttpConnection.POST);
hc.setRequestProperty ("Content-Type", "application/x-www-form-urlencoded");
hc.setRequestProperty ("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
hc.setRequestProperty ("Content-Language", "en-US");
System.out.println ("Posting to the URL: " + entry.getVectorParams());
//open the output stream to send the post parameters
//os=hc.openOutputStream();
oj=(ObjectOutputStream)hc.openOutputStream();
//writing post parameters
String[] bg=entry.getVectorParams();
oj.writeObject(bg);
Please give a suggestion.
I checked my URL, it is correct and regarding Connector.open(), i pasted it twice here, not in my actual code. Is there anything else that I am doing wrong?
The System.out.println("Posting to the URL: " + entry.getVectorParams()), this only prints the post parameters, I have the serverurl passed in here:
String serverURL=entry.getUrl();
hc=(HttpConnection)Connector.open(serverURL, Connector.READ_WRITE, true);
My server URL is : http://localhost:8080/Web/gServer.jsp

The value of your serverURL variable must not be a valid URL. Try printing it out, and checking.
You have this debug statement:
System.out.println ("Posting to the URL: " + entry.getVectorParams());
but that is printing out the params, not the url. You should print out the serverURL variable.
Also, you are calling Connector.open() twice in a row. There's no need for that.
Update: I also think there could be a problem with the way you're writing the POST parameters to your connection's OutputStream. I wouldn't use an ObjectOutputStream. See something like this for an example of making J2ME POST calls. Basically, you make a String of the POST parameters, separated by &, and then use String.getBytes() to convert to a byte[] for writing to the OutputStream.

Related

Add flag to UnityWebRequest

I am trying to make a POST request to webpage that expects the --data field to be filled with some data to be processed. I'm pretty much trying to recreate this curl request, but with UnityWebRequest.
curl -X POST http://localhost:8000/clic/say?text=Make+the+gene+set --data '{"geneSetMembers":["UST"],"geneSetName":"selection0"}'
The UnityWebRequest documentation mentions that GET requests don't set any flags other than the url, but it's not clear if no other custom options exist for posts. Is there some way to format a WWWform or something that will hold the data such that the server will recognize it?
var form = new WWWForm();
// some way to plug in the jsonified data to the form
webRequest = UnityWebRequest.Post(url + route + to_say, form);
webRequest.downloadHandler = new DownloadHandlerBuffer();
webRequest.SetRequestHeader("Content-Type", "application/json");
webRequest.SendWebRequest();
// etc etc
I've tried just giving the form a field named "data" a la
form.AddField("data", "{ \"geneSetMembers\":[\"UST\"],\"geneSetName\":\"selection0\"}");
but the server does not like it, saying it "got error Invalid JSON literal name: data" So clearly that's the wrong syntax for it
EDIT: put lines in the same order they were in original code. Sorry, I have commented lines between them
Maybe your server doesn't like to receive the data as a field called data.
This ofcourse depends totally on the PHP code we don't see since you didn't share that part. b
But at least I can tell you that --data or also simply -d in curl refer to the entire data section and is not a field called data.
You could try to instead use a MultiPartFormDataSection passing just the data itself without a specific field name
var data = "{\"geneSetMembers\":[\"UST\"],\"geneSetName\":\"selection0\"}";
var form = new List<IMultiFormPart>{ new MultiPartFormDataSection(data) };
webRequest = UnityWebRequest.Post(url + route + to_say, form);
yield return webRequest.SendWebRequest();
which is now sent as content-type multipart/form-data though ...
Another alternative if your server really needs to receive a content-type application/json might be to "manually" compose the request e.g. like
var data = "{\"geneSetMembers\":[\"UST\"],\"geneSetName\":\"selection0\"}";
var request = new UnityWebRequest(url + route + to_say, "POST");
var bodyRaw = Encoding.UTF8.GetBytes(data);
request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
Though of you look close now this seems actually not to be the case since if you read the man curl
(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded
which is actually exactly the default content type used by the simple string version of UnityWebRequest.Post.
So thinking about it it should actually be as simple as using the pure string version of UnityWebRequest.Post:
var data = "{\"geneSetMembers\":[\"UST\"],\"geneSetName\":\"selection0\"}";
var request = UnityWebRequest.Post(url + route + to_say, data);
yield return request.SendWebRequest();

Invalid nonce kraken

I am getting {"error":["EAPI:Invalid nonce"]} while calling https://api.kraken.com/0/private/AddOrder end point.
passing following params in form of json:
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("pair", "XXBT");
jsonObject.accumulate("type ", "sell");
jsonObject.accumulate("ordertype ", "market");
jsonObject.accumulate("price", "2");
jsonObject.accumulate("volume", "1");
Setting API-Key and API-Sign as well.
nonce = String.valueOf(System.nanoTime());
Generating nonce using above logic. Any idea where I am going wrong?
Try increase option Nonce Window to 5000-10000. You can find this option here.

SendGrid incoming mail webhook - how to save the JSON format email data into my application folder in C#

This is regarding Sendgrid incoming mail webhook, I have referred this URL SendGrid incoming mail webhook - how do I secure my endpoint, and got some idea how to go about this, but, as I am new to MVC / WebAPI, could anyone give me the controller method code snippet to catch the JSON format HTTP post and save to my application folder.
This is the solution I found after googling and with slight modifications:
[HttpPost, HttpGet]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public async Task Post()
{
if (Request.Content.IsMimeMultipartContent("form-data"))
try
{
//To get complete post in a string use the below line, not used here
string strCompletePost = await Request.Content.ReadAsStringAsync();
HttpContext context = HttpContext.Current;
string strFrom = context.Request.Form.GetValues("from")[0];
string strEmailText = context.Request.Form.GetValues("email")[0];
string strSubject = context.Request.Form.GetValues("subject")[0];
//Not useful I guess, because it always return sendgrid IP
string strSenderIP = context.Request.Form.GetValues("sender_ip")[0];
}
catch (Exception ex)
{
}
}
I tried, retrieving the values as
String to = context.Request.Params["to"];
but, the value returned is not consistent, i.e. most of the times it is returning null and occasionally returns actual value stored in it.
If anyone have a better solution, please let me know.
Thank you
If for some reason ["to"] doesn't work for you, try to get ["envelope"] value,
context.Request.Form.GetValues("envelope")[0]
which looks like
{"to":["emailto#example.com"],"from":"emailfrom#example.com"}

Handling form data for application/x-www-form-urlencoded contentType

I have a textarea in a jsp page and the contents of that are processed in a Servlet.
I thought the contentType was multipart so I figured I'd use getFormField() and getString() methods to extract the values but this throws an exception saying
the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/x-www-form-urlencoded
When I use request.getParameter("textAreaID") it is always null. How do I handle this situation? Any help would be appreciated. Please let me know if the question is not framed in a proper manner before downvoting. Thanks in advance.
If u want to extract values of many fields,you can use getParameterNames() method
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements())
{
String parameter = (String) paramNames.nextElement();
String parameterValue = (String) request.getParameter(parameter);
System.out.println("*****" + parameter + " - " + parameterValue);
}

How To URLEncode Facebook Post Data in C#

I am rewriting code from http://blog.blackballsoftware.com/2010/11/03/making-a-facebook-wall-post-using-the-new-graph-api-and-c/ to create a class to post to Facebook. The code works as long as I do not URLEncode the post data. For example: If the post data is "message=Test,please ignore" then it works. If I URLEncode the same data into "message%3dTest%2cplease+ignore" then I get the error {"error":{"message":"(#100) Missing message or attachment","type":"OAuthException","code":100}}.
Should the Post data be URLEncoded? I think it should because if I post a message like this, "Test&Message", then only the word Test appears.
Relevant code is below. If postParams = HttpUtility.UrlEncode(postParams); is commented out, then the code works. If not, Facebook returns the error that the message is missing.
postParams = HttpUtility.UrlEncode(postParams);
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postParams);
webRequest.ContentLength = bytes.Length;
System.IO.Stream os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
try
{
var webResponse = webRequest.GetResponse();
}
catch (WebException ex)
{
StreamReader errorStream = null;
errorStream = new StreamReader(ex.Response.GetResponseStream());
error = errorStream.ReadToEnd() + postParams;
}
The answer can be found on Stackoverflow at C# Escape Plus Sign (+) in POST using HttpWebRequest. Use Uri.EscapeDataString and not URLEncode. Encode the parameter value only and not the equals sign after the parameter name. Example: message=Test%2Cplease%26%20ignore works but message%3dTest%2Cplease%26%20ignore does not work because the equals after the parameter name is encoded as %3d.