Typically, when I make a POST or GET HTTP call from a web app, the hash is available directly from the params hash:
#user = User.find(params[:id])
However, I have sent content type 'application/json' from an Android app, as so:
JSONObject holder = new JSONObject();
JSONObject userObj = new JSONObject();
userObj.put("username", params.get("name"));
userObj.put("uid", params.get("uid"));
userObj.put("image", params.get("image"));
userObj.put("provider", params.get("provider"));
holder.put("user", userObj);
query = holder.toString();
url = new URL("http://10.0.2.2:3001/users/auth/facebook/callback.json ");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
And when I looked at the logs, the data is nicely formatted:
Processing by OmniauthCallbacksController#facebook as JSON
Parameters: {"user"=>{"username"=>"John Dough", "uid"=>"11111222444", ...
However, I cannot access the params hash as so:
params_user # => nil
def params_user
params[:user].permit!
end
Why can I not access the params hash when it is clearly available?
If I try to access it like this:
params.parameters['user']
It tells me the parameters method of params is protected. But that is the only place I see my data when I use the debugger.
NoMethodError (protected method `parameters' called for #<ActionController::Parameters:0x007fc51d1f9e08>):
not sure which version of Rails you're using but in modern Rails you do this:
def params_user
params.require(:user).permit(:email, :name, :other_attributes)
end
Related
I have been looking at this over a week now and i cant find where the null pointer problem lies, this is bugging me completely and the teacher Google is not very helpful. I cant find what the real problem here...and its driving nuts! :/
I am trying to send a notification to Firebase and it does not go beyond the streamwriter, i have checked that conn is not null or the json but they are all looking good. If i use a RESTclient i can send a message successfully with correct ID key and message and it is recived by the app. The emulated phone has internet connection.
The error thrown in run looks like this:
com.android.okhttp.internal.huc.HttpURLConnectionImpl:https://fcm.googleapis.com/fcm/send. Attempt to invoke interface method 'void om.android.okhttp.internal.http.HttpStream.writeRequestHeaders(com.android.okhttp.Request)' on a null object reference.
my code:
String FCM_URL = "https://fcm.googleapis.com/fcm/send";
URL url = new URL(FCM_URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
//set method as POST or GET
conn.setRequestMethod("POST");
conn.setConnectTimeout(3000);
//pass FCM server key
conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);
//Specify Message Format
conn.setRequestProperty("Content-Type", "application/json");
conn.connect();
//Create JSON Object & pass value
JSONObject infoJson = new JSONObject();
infoJson.put("body", message);
infoJson.put("title", "Test send:");
JSONObject json = new JSONObject();
json.put("to", tokenId);
json.put("collapse_key", "type_a");
json.put("notification", infoJson);
//Add data to json string
JSONObject datacon = new JSONObject();
datacon.put("body","First notification");
datacon.put("title", "Collapsing A");
datacon.put("key_1","Data for key 1");
datacon.put("key_2","Hello, test two");
json.put("data", datacon);
BufferedWriter out =
new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
out.write(json.toString());
out.flush();
out.close();
Any help or pointers would be greatly appreciated!
It seems there is a typo, set instead of add
conn.setRequestProperty("Content-Type", "application/json");
and after that, to be able to write
conn.connect();
I have prepared one API, and I want to send one specific data with json posting.
My code works fine during working with Fiddler or site side.
But the problem is why some character didn't send, when we use Android version as a client device.
For example:
string a="mn✈" // correct on any device (android,site,Fiddler,...)
string b="mn✉" //correct on any device except(android) //getting 500 reponse
String requestURL = Utils.SERVER_URL + "PostJsonFeatures";
HttpURLConnection conn = (HttpURLConnection) new URL(requestURL).openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
JSONObject postDataParams = new JSONObject();
postDataParams.put("Features", getAttributes());
postDataParams.put("productId", productId);
postDataParams.put("groupId", catId);
postDataParams.put("brandId", PrefManager.getInstance(context).getCompanyId());
postDataParams.put("languageId", PrefManager.getInstance(context).getLanguageApi());
DataOutputStream printout = new DataOutputStream(conn.getOutputStream ());
printout.write(postDataParams.toString().getBytes());
printout.flush ();
printout.close ();
You can decode to string and pass in url.
String parseString = URLDecoder.decode(URLEncoder.encode(myString, "UTF-8"), "ISO-8859-1");
I want to add header "Content-Type" "application/json". But I am not been able to do this due to api 23 in android.
OutputStream os= null;
os=httpclient.getOutputStream();
BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(os));
JSONObject jsonobj = new JSONObject();
jsonobj.put("Name","alpha");
jsonobj.put("Status","Active");
jsonobj.put("Type","Admin");
jsonobj.put("Address","beta");
jsonobj.put("Password","333");
jsonobj.put("PhoneNumber",123);
bw.write(jsonobj.toString());
os.close();
I assume that you are trying to make a network call to some API which expects you to add Headers to the HTTP calls you are making and the content-type data is JSON.
If that is your case then you would have to specify the Headers to the instance to respective class with which you are trying to connect..
for example if you are using HttpURLConnection
then it would look like this
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST"); // hear you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
httpURLConnection.setRequestProperty("Content-Type", "application/json"); // here you are setting the `Content-Type` for the data you are sending which is `application/json`
httpURLConnection.connect();
and when you are posting some data to the instance of the HttpURLConnection you can do it like this...
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("para_1", "arg_1");
jsonObject.addProperty("para_2", "arg_2");
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();
please help me out with this problem.
I want to make a POST call with JSON data that should appear in body to request but i am not able to do that. I made POST call and getting data but data is not in JSON format.
Code :
data = "{'mobile':'"+mobile_number+"','password':'"+mypassword+"'}";
byte[] dataPost = data.getBytes();
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
urlConnection.setInstanceFollowRedirects(false);
urlConnection.setRequestProperty("Accept", "application/json");
//urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("charset", "UTF8");
urlConnection.setUseCaches(false);
OutputStream os = urlConnection.getOutputStream();
os.write(dataPost);
os.close();
Result is coming like below
body:
{'a':'b','c':'d'}:""
Please Help me. i am new to android Development.
Thanks
Problem:
Accented characters cause Jackson to fail in the object mapping stage when sending a POST request from the Android application, but work fine when using the Advanced Rest Client plugin for chrome.
This leads me to believe the issue is related to how the Android code is sending the request, but I've tried adding explicit references to UTF-8 with no success. When I debug the process during execution all values seem correct.
Context:
I'm developing an application on Android that connects to a server that exposes endpoints implemented in Spring. The server is developed using Spring MVC and makes use of Google App Engine.
A specific endpoint can receive user inputted values, which may include accented characters.
The payload follows this structure, which maps to an object on the server side:
{
"senderEmail":"<email here>",
"token":"<token here>",
"friendList":["<email here>"],
"base64Value":"<base64 encoded value here>",
"message":"ú"
}
When this payload is sent from the REST client the server processes the request fine and returns a 200. When sending it from the Android application, the following exception is thrown:
org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver resolveException: Resolving exception from handler [public org.springframework.http.ResponseEntity<java.lang.Object> com.web.controllers.PictureController.postPic(com.web.controllers.viewobjects.PostPicRequest)]: org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Invalid UTF-8 middle byte 0x22
at [Source: com.google.apphosting.runtime.jetty.RpcConnection$RpcRequestInput#832f7f; line: 1, column: 15] (through reference chain: com.web.controllers.viewobjects.PostPicRequest["message"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x22
at [Source: com.google.apphosting.runtime.jetty.RpcConnection$RpcRequestInput#832f7f; line: 1, column: 15] (through reference chain: com.web.controllers.viewobjects.PostPicRequest["message"])
Code:
The Android code that sends the request (edited for public viewing):
URL url = new URL( URL_POST );
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept-Encoding", "");
String base64Value = "blabla"
//Get JSON
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate(Api.POST_PARAM_BASE64VALUE, base64Value);
jsonObject.accumulate(Api.POST_PARAM_SENDEREMAIL, senderEmail);
jsonObject.accumulate(Api.POST_PARAM_TOKEN, token);
jsonObject.accumulate(Api.POST_PARAM_MESSAGE, message);
//Make array from friends string
String[] allFriendsArray = friendList.split(",");
JSONArray friendsJsonArray = new JSONArray();
for(String x : allFriendsArray) {
friendsJsonArray.put(x.trim());
}
jsonObject.accumulate(Api.POST_PARAM_FRIENDLIST, friendsJsonArray);
jsonObject.accumulate(Api.POST_PARAM_ISANONYMOUS, isAnonymous);
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();
int httpResponseCode = urlConnection.getResponseCode();
Got the same response when using the following code in Android:
HttpPost httpPost = new HttpPost(Api.URL_POST);
httpPost.setEntity(new StringEntity(jsonObject.toString()));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse resp = new DefaultHttpClient().execute(httpPost);
The Spring method definition, which is contained in a controller annotated with #RestController:
#RequestMapping(value= "/post", method = RequestMethod.POST)
public ResponseEntity<Object> post(#RequestBody PostRequest postRequest) { /*code here*/}
Found the following snippet of code ( here ) that properly encodes the payload and is received correctly on the server side too.
Thanks everyone!
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write( jsonObject.toString() );
writer.close();
os.close();
int httpResponseCode = urlConnection.getResponseCode();