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.
Related
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.
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.
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
I use a simple WebServer from http://www.java2s.com/Code/Java/Network-Protocol/AverysimpleWebserverWhenitreceivesaHTTPrequestitsendstherequestbackasthereply.htm
and Android code from Sending json object via http post method in android
In my main Activity:
AsyncT asyncT = new AsyncT();
asyncT.execute();
Class:
class AsyncT extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL(""); //Enter URL here
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST"); // here 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();
JSONObject jsonObject = new JSONObject();
jsonObject.put("para_1", "arg_1");
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
The connection is established without any errors ("HostConnection::get() New Host Connection established"). However, I am not able to get in my Java server any information from the request. When I read from input stream
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println(in);
I get java.io.BufferedReader#4d7hge12
And this outputs nothing:
String line;
while ((line = in.readLine()) != null) {
if (line.length() == 0)
break;
System.out.println(line);
}
Don't re-invent the wheel and use a library for this.
For example okhttp:
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
If you want to call a REST-API you can use retrofit (which is build ontop of okhttp)
Assuming you're doing this as a learning exercise, so using another library isn't what you're looking for, I would suggest a couple of things:
(1) install Wireshark and see what the actual response coming back the server is, does it look sensible?
(2) break that line of code out into separate lines, is the InputStream / InputStreamReader null?
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