Inserting JSON data to mLab database using Android application - java

I am new to android and mongodb.
I have problem with inserting data to my mLab database using my android application.
My code is this:
final class MongoLabSaveData extends AsyncTask<Object, Void, Boolean> {
#Override
protected Boolean doInBackground(Object... params) {
SignupData signupData = (SignupData) params[0];
Log.d("Sign_Up", ""+signupData);
try {
SupportDataAPI sd = new SupportDataAPI();
URL url = new URL(sd.buildSignupSaveURL());
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("PUT");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
osw.append(sd.createSignupData(signupData));
osw.flush();
osw.close();
if(connection.getResponseCode() <205)
{
return true;
}
else
{
return false;
}
} catch (Exception e) {
e.getMessage();
Log.d("Got error", e.getMessage());
return false;
}
}
}
Here, the data gets inserted to every 0th index of json data due to this line:
SignupData signupData = (SignupData) params[0];
How can I make this in such a way that it appends my json data with the existing data. Not in the 0th index.

Related

Java HttpURLConnection is not sending a body

I'm trying to send a PUT request with a body to my API in my Android app with Java. I'm using the java.net HttpURLConnection and the request gets through. But without the body.
I refactored my code over and over again but it still does not work, at the moment I have following Task:
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
JSONObject body = new JSONObject();
try {
body.put("title", title);
body.put("content", content);
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("PUT");
urlConnection.addRequestProperty("username", username);
urlConnection.addRequestProperty("password", password);
urlConnection.addRequestProperty("Content-Type", "application/json; utf-8");
urlConnection.addRequestProperty("Accept", "application/json");
urlConnection.setDoOutput(true);
try(OutputStream os = urlConnection.getOutputStream()){
byte[] input = body.toString().getBytes("utf-8");
os.write(input, 0, input.length);
}
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1){
char current = (char) data;
result += current;
data += current;
data = reader.read();
}
return result;
}catch (Exception e){
e.printStackTrace();
return null;
}
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
But this code leads always to an empty body.
EDIT
When changing content type to application/x-www-form-urlencoded the server gets the body. But this way I don't get a JSON file for further processing it.
The java code is working correctly. The API wasn't accepting JSON. Other languages worked without problems.
Server Info
Node.js
Express
Body Parser
I didn't add app.use(bodyParser.json());

How to get and use HTTPResponse message from a DJANGO server

How can I get the response message returned from my DJANGO view and place it into a textview? Most of the answers talk about using Httpresponse but as I've read, it has be deprecated. I'm using SDK v28.
Java code in Android Studio:
private class HTTPAsyncTask_wdgt extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
try {
return HttpPost_wdgt(urls[0]);
} catch (JSONException e) {
e.printStackTrace();
return "Error!";
}
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
}
private String HttpPost_wdgt(String myUrl) throws IOException, JSONException {
URL url = new URL(myUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
JSONObject jsonObject = buildJsonObject_wdgt(); //Just takes some data from the app and returns JSON to be posted.
setPostRequestContent_wdgt(conn, jsonObject);
conn.connect();
return conn.getResponseMessage()+"";
}
private void setPostRequestContent_wdgt(HttpURLConnection conn,
JSONObject jsonObject) throws IOException {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(jsonObject.toString());
writer.flush();
writer.close();
os.close();
}
Django view: (Right now it just returns 'mac' from the posted JSON)
#csrf_exempt
def req_exec(request):
ret = request.POST
data = json.loads(request.body)
return HttpResponse(data['mac'])
I normally use OKHttp for getting and processing requests, here is a Vogella tutorial helping to get start.

Send data(Client_id=1,Staff_id=2) from android application to tomcat server

i want to send data from android application to tomcat java server.
Data is just one is client_id which is 1 and second is staff_id which is 2.
after authenticate the client id and staff id from tomcat show me a toast of success....please help...
Code is here
public class MyAsyncTasks extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// display a progress dialog for good user experiance
}
#Override
protected String doInBackground(String... params) {
// implement API in background and store the response in current variable
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://192.168.1.13:8080/digitaldisplay/s/m/data");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
current += (char) data;
data = isw.read();
System.out.print(current);
}
// return the data to onPostExecute method
return current;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
return current;
}
#Override
protected void onPostExecute(String s) {
Toast.makeText(Register.this, "success", Toast.LENGTH_SHORT).show();
Log.d("data", s.toString());
// dismiss the progress dialog after receiving data from API
try {
// JSON Parsing of data
JSONArray jsonArray = new JSONArray(s);
JSONObject oneObject = jsonArray.getJSONObject(0);
// Pulling items from the array
client = Integer.parseInt(oneObject.getString("client"));
staff = Integer.parseInt(oneObject.getString("staff"));
} catch (JSONException e) {
e.printStackTrace();
}
} }}
The logic in your code looks off to me. This is the pattern I usually follow when making a REST call from an activity using HttpURLConnection:
try {
String endpoint = "http://192.168.1.13:8080/digitaldisplay/s/m/data";
URL obj = new URL(endpoint);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST"); // but maybe you want GET here...
con.setConnectTimeout(10000);
con.setDoInput(true);
con.setDoOutput(true);
JSONObject inputJSON = new JSONObject();
inputJSON.put("Client_id", 1);
inputJSON.put("Staff_id", 2);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(inputJSON.toString());
writer.flush();
writer.close();
os.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response);
} catch (SocketTimeoutException se) {
// handle timeout exception
responseCode = -1;
} catch (Exception e) {
// handle general exception
responseCode = 0;
}
The only major change in adapting the above code for GET would be that you wouldn't write your input data to the connection. Instead, you would just append query parameters to the URL. I am possibly guessing that you need POST here, since your URL doesn't have any query parameters in it.

Delivering data between two classes

I'm trying search a beacon device and get the Majoy & Minor, then send the data to request, but I got the problems is I don't know how to send the data between the two part ..
I want to put the beacon.getMajor()
to jsonObject.put("uuid", a)
Thank you !
Here is my code.
private List<String> placesNearBeacon(Beacon beacon) {
int a = beacon.getMajor();
final String b = String.valueOf(beacon.getMajor());
Log.v("show", String.valueOf(a));
Intent intent = new Intent(this,AsyncLogin.class);
intent.putExtra("MAJOR",a);
startActivity(intent);
if (a == 258){
new AsyncLogin().execute(String.valueOf(a));
}
String beaconKey = String.format("%d:%d", beacon.getMajor(), beacon.getMinor());
return Collections.emptyList();
}
enter code here
private class AsyncLogin extends AsyncTask<String, String, String>
{
HttpURLConnection conn;
URL url = null;
Uri a = new Intent().getData();
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://etriplay.com/app/beacon_GetInform.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "exception";
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// JSON
JSONObject jsonObject = new JSONObject();
jsonObject.put("userid", "membe00001");
jsonObject.put("mail", "test#mail.com");
jsonObject.put("uuid", a);
Log.v("v", String.valueOf(jsonObject));
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(String.valueOf(jsonObject));
writer.flush();
writer.close();
os.close();
conn.connect();
In this case If you want object or something to put in json you can do ie by-:
try
{
jsonObject.put("value",chatMessage.getDate());
}
catch (JSONException e)
{
e.printStackTrace();
}
as in jsonobject.put("key",value);
You can assign the int value,string value,boolean value or whatever you want

Android HttpUrlConnection not working

Basically, I'm trying to connect to a web interface through an Android App.
I managed to send commands to the form successfully using HttpClient. However, I want to accomplish this using HttpUrlConnection as recommended here http://android-developers.blogspot.com/2011/09/androids-http-clients.html with the intention of having a faster and more energy efficient connection.
URL url = new URL("http://" + mIpAddress + ":" + mPort + "/command.html");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(URLEncoder.encode("parameter=" + value, "UTF-8");
writer.flush();
writer.close();
os.close();
connection.connect();
Edit: No exceptions are being thrown since the code is executing just fine, the request is just probably not in the expected format by the server?
connnection.getInputStream() was required for the POST to work. Fixed.
Here is what I use to send http requests using HttpURLConnection, notice that the connection.connect() is right after setting up the HttpURLConnection not at the end, also the setDoInput makes the request POST instead of the default get,
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//conn.setReadTimeout(10000 /* milliseconds */);
// conn.setConnectTimeout(15000 /* milliseconds */);
//conn.setRequestMethod("GET");
//conn.setDoInput(true); //* uses POST
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
//String data = convertStreamToString(stream);
int sz = stream.available();
byte[] b = new byte[sz];
stream.read(b);
stream.close();
String data = new String(b);
Just add one line
connection.getRequestMethod();
and it will work.
I dont know why but this works for me after I have spent a whole day on it!
Could you provide more information, like Exceptions, or the servers response? Does the server receives a your request?
However, I recommend you to use okhttp which has been build on top of HttpUrlConnection
To share Data using HttpUrlConnection class
Here is Simple Connection class this Will Help you to Connect With WS , and to pass data using JSON parsing ..
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class CommonConnectionClass {
JSONObject jsonObject;
public JSONObject getConnection(String u,JSONObject object){
try {
//URL url=new URL("https://e-gurukulam.000webhostapp.com/public_html/project/login.php"+u+".php");
URL url=new URL("http://"+new Connection_Url_Setter().urlIp+"/classroom/"+u+".php");
// URL url=new URL("http://192.168.43.120/classroom/"+u+".php");
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type","application/json; charset=utf-8");
httpURLConnection.setRequestProperty("Accept","application/json; charset=utf-8");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
if(object!=null) {
DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.write(object.toString().getBytes());
}
int code=httpURLConnection.getResponseCode();
if(code== HttpURLConnection.HTTP_OK){
String inputLine;
StringBuilder stringBuilder=new StringBuilder();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
while((inputLine=bufferedReader.readLine())!=null){
stringBuilder.append(inputLine);
}
jsonObject=new JSONObject(stringBuilder.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
}
To use this class i use the Asyn class Like,...
class userNameFetchTask extends AsyncTask<Void, Void, JSONObject> {
JSONObject object, jsonObject, json;
JSONArray jsonArray;
ArrayList<CreateGroupModel> lidList = new ArrayList<>();
String lid, name;
#Override
protected void onPreExecute() {
jsonObject = new JSONObject();
try {
jsonObject.put("lid", sp.getString("lid", null));
} catch (JSONException e) {
e.printStackTrace();
}
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(Void... voids) {
object = new JSONObject();
CommonConnectionClass commonConnectionClass = new CommonConnectionClass();
object = commonConnectionClass.getConnection("selectUserForGroup", jsonObject);
return object;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
jsonArray = new JSONArray();
try {
jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
CreateGroupModel model = new CreateGroupModel();
json = jsonArray.getJSONObject(i);
model.setLid(json.getString("relative_lid"));
model.setName(json.getString("name"));
model.setEmail(json.getString("email"));
model.setImage(json.getString("image"));
lidList.add(model);
}
viewstudentsadapterForCreateGroup viewstudentsadapterForCreateGroup = new viewstudentsadapterForCreateGroup(getApplicationContext(), lidList, createGroup_Activity.this);
listView.setAdapter(viewstudentsadapterForCreateGroup);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
In my case, it was actually NetworkOnMainThreadException thrown but not shown clearly in Logs

Categories