I am developing an Android app with a NodeJS backend server. I am having problems authenticating the users when requests are made to different pages after the user is logged in.
Once I log in, i store the set-cookie value in SharedPrefs. Now when I make a POST request, I am sending the set-cookie value in the header, i.e. con.setRequestProperty("set-cookie", cookie); for authenticating the user on the backend using req.user.authenticate.
However, req.user is undefined and hence the request fails. What could be wrong over here? Thanks.
Below is my POST request code.
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "\"Mozilla/5.0\"");
con.setDoOutput(true);
JSONObject jsonParam = new JSONObject();
try {
jsonObject.accumulate("set-cookie", cookie);
} catch (JSONException e) {
e.printStackTrace();
}
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.write(jsonParam.toString());
out.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code:"+responseCode);
Send data in this format
String data = "";
InputStream inputStream = null;
try{
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("set-cookie", cookie);
data = jsonObject.toString();
Log.d("json data",data);
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(CHECK_WEBSERVICE_URL);
StringEntity se = new StringEntity(data);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
System.out.print(result);
}catch (Exception e){
e.printStackTrace();
}
Related
When I used HttpUrlConnection to send POST request from Android to ASP.net Web API. It seems not working.
String baseUrl = "http://<IP Address>/Save/Document";
URL url = new URL(baseUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
JSONObject ap = new JSONObject();
// Where data is a JSON string
// Like [{Test: 1}, {Test: 2}]
ap.put("",new Gson().toJson(data));
OutputStreamWriter ap_osw= new OutputStreamWriter(conn.getOutputStream());
ap_osw.write(ap.toString());
ap_osw.flush();
ap_osw.close();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder response = new StringBuilder();
while ((output = br.readLine()) != null) {
response.append(output);
response.append('\r');
}
String mes = response.toString();
Log.i("INFO", mes);
conn.disconnect();
When executing the above code, it will have an FileNotFoundException in
conn.getInputStream()
I also tried to implement source code in HttpClient style.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(baseUrl);
try {
StringEntity se = new StringEntity((new Gson()).toJson(data));
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(httpPost);
InputStream inputStream = response.getEntity().getContent();
String result = "";
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
Log.i("RESPONSE", result);
} catch (Exception ex) {
Log.i("Exception", ex.getMessage());
}
return output;
And this time, it shows "The requested resource does not support http method 'get'".
I have no ideas how to implement the POST request method to send data from Android to ASP.net Web API. Any recommendations?
Finally, the following coding is my ASP.net Web API for reference.
[HttpPost]
[Route("Save/Document")]
public HttpResponseMessage Post([FromBody]string model)
{
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(model, System.Text.Encoding.UTF8, "text/plain");
return resp;
}
Finally, I got a solution to fix this problem. It is due to the POST data in request body can not be read from Web API.
When the request Content-Type is "application/json",
Using string, The request body should be a plain text (e.g. "Text Message").
[FromBody] string inStr
Using self-defined class, The request body should be a json string
(e.g { KEY: VALUE })
[FromBody] YourClass inObj
Using array of self-defined class, The request body should be a json array string (e.g [{ KEY: VALUE }])
[FromBody] YourClass[] inObj
And the self-defined class should be like as following:-
class YourClass {
public string KEY { get; set; }
}
Btw. Thanks for all reply and useful information.
I am trying to fetch an authorization key from a server. In the documentation they state that I can retrieve one by executing the following curl command:
$ curl --data "grant_type=authorization_code&code=603372224265" https://gerard2.zportal.nl/api/v2/oauth/token`
I have followed the instructions from stackoverflow and produced the following:
#Override
protected String doInBackground(String... params) {
mAuthorizationCode = params[0];
mSchoolCode = params[1];
HttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://" + mSchoolCode + ".zportal.nl/api/v2/oauth/token");
try{
List<NameValuePair> nameValuePairs = new ArrayList<>(2);
httppost.setHeader("Content-Type", "application/json");
httppost.setHeader("Accept", "application/json");
nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
nameValuePairs.add(new BasicNameValuePair("code", mAuthorizationCode));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
HttpParams parameters = httppost.getParams();
HttpConnectionParams.setConnectionTimeout(parameters, 45000);
HttpConnectionParams.setSoTimeout(parameters, 45000);
HttpResponse response = httpClient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
while((line = reader.readLine()) != null){
Log.e(LOG_TAG, line);
}
}catch(ClientProtocolException e){
Log.e(LOG_TAG, "Error", e);
}catch(IOException e){
Log.e(LOG_TAG, "IO Error", e);
}
return null;
}
The response the server sends me is:
E/ScheduleRetriever: {"response":{"status":500,"message":"Intern probleem op het portal.","details":"class org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'grant_type' is not present","eventId":767369,"startRow":0,"endRow":0,"totalRows":0,"data":[]}
While I did include the POST_parameter "grant_type". Can someone help me figure out why the server says that it did not receive the parameter grant_type?
Thanks.
*EDIT: The code I used expired apparently. Generated a new one and it totally works. Thanks!
You shouldn't be overriding the Content-Type of the POST request to application/json using the line httppost.setHeader("Content-Type", "application/json");
This is most likely causing the server to misinterpret the data since the Content-type of the request should be application/x-www-form-urlencoded.
Remove the following line and it should work:
httppost.setHeader("Content-Type", "application/json");
I need to send string (vietnamese) from Android devices to server like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.URL.UPDATE_CURRENT_STATUS);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("location", "Thạch thất Hanoi "));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
int respnseCode = response.getStatusLine().getStatusCode();
if (respnseCode == 200) {
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
But when server gets the string, its not like
Thạch thất Hanoi
its become
Thạch Thất Hanoi
My code in server side:
#RequestMapping(value = "/UpdateCurrentStatus", method = RequestMethod.POST, produces = { "application/json" })
#ResponseBody
public MessageDTO updateCurrentStatus(
#RequestParam Map<String, String> requestParams) throws TNException {
String location = requestParams.get("location");
System.out.println(location);
MessageDTO result = driverBO.updateCurrentStatus(location);
return result;
}
How can I resolve this problem? Thank you.
Did you set you android httpclient Content-Type header to application/json; charset=utf-8 instead of "application/json"?
I think your problem is that the content entity location you sent is encoded correctly in UTF-8 but server failed to acknowledge UTF-8. clarify it in Content-Type header.
You can diagnose http content and its header with great http monitoring tool Fiddler.
-EDIT BELOW-
Relace your UrlEncodedFormEntity as below. Set header to application/json; charset=utf-8 as I described earlier. it's good to set it up still.
JSONObject jsonParam = new JSONObject();
jsonParam.put("location", "Thạch thất Hanoi ");
StringEntity entity = new StringEntity(jsonParam.toString(), "UTF-8");
httppost.setEntity(entity);
in my app i need to post data to an url to register a new user. Here is the url
http://myurl.com/user.php? email=[EMAIL]&username=[USERNAME]&password[PASS]&img_url=[IMG]
If I do that correctly I should get this message:
{"success":true,"error":null}
or if not {"success":false,"error":"parameters"}
Can somebody guide me through this and tell me how can I do it.
first :
you need to perform all network tasks in an Async thread using:
public class PostData extends AsyncTask<String, Void, String>{
{
#Override
protected String doInBackground(String... params) {
//put all your network code here
}
Second:
create your http request:
i am assuming email, username and IMG as variables over here.
String server ="http://myurl.com/user.php? email=[" + EMAIL + "]&username=[" + USERNAME + "]&password[" + PASS + "]&img_url=["+IMG + "]";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(server);
//httppost.setHeader("Accept", "application/json");
httppost.setHeader("Accept", "application/x-www-form-urlencoded");
//httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
third:
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("JSONdata", Object));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
try {
HttpResponse response =httpclient.execute(httppost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Now simple query your response handler i.e. response in this case.
Don't forget to add INTERNET permission in your androidManifest.xml
Hope this helps!
Use a HTTP client class, and format your URL via a specific URI constructor. Create a HTTP post, optionally set the entity, headers, etc, execute the post via the client, receive a HTTP response, pull the entity out of the response and process it.
EDIT for example:
HttpClient httpclient = new DefaultHttpClient();
URI uri = new URI("http",
"www.google.com", // connecting to IP
"subpath", // and the "path" of what we want
"a=5&b=6", // query
null); // no fragment
HttpPost httppost = new HttpPost(uri.toASCIIString);
// have a body ?
// post.setEntity(new StringEntity(JSONObj.toString()));
// post.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
Reader r = new InputStreamReader(entity.getContent());
// Do something with the data in the reader.
I'm trying to send notification for both Android & iOS using non-Latin charset.
I notice when I send message from Android to iOS using non-Latin charset, message displayed on iPhone as "????", since the Java server side for iOS and Android are the same, I assume the problem is how I send the request from Android handset, notice message from iOS to iOS works fine.
below is the code that I'm using to open network connection and sending the request, please, let me know if it's OK.
byte[] bytes = body.getBytes(/*"UTF-16"*//*"ISO-8859-1"*/"UTF-8");
HttpURLConnection conn = null;
StringBuilder stringBuilder = new StringBuilder();
try {
conn = (HttpURLConnection) url.openConnection();//conn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
Log.d("send message", "Coud Send Message, No Internet Connection Avilable.");
throw new IOException("Post failed with error code " + status);
}
InputStream in = new BufferedInputStream(conn.getInputStream());
// readStream(in);
int b;
while ((b = in.read()) != -1) {
stringBuilder.append((char) b);
}
check below code it works for me, i have also same issue,
to get Data from server,
String is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs2));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs2,
HTTP.UTF_8));
HttpResponse responce = httpclient.execute(httppost);
HttpEntity entity = responce.getEntity();
is = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
// TODO: handle exception
Log.d("call http :", e.getMessage().toString());
is = null;
}
return is;
hope it may help you.