Android POST request with JSON Constraint - java

Error which i am facing
The Error Tells me on class execution to create and inner class or create a new class
But i am executing it inside a button which is in onCreate method so please if anybody can guide me how to proceed ....
The Main Class
private class SendDeviceDetails extends AsyncTask {
#Override
protected String doInBackground(String... params) {
String data = "";
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes("PostData=" + params[1]);
wr.flush();
wr.close();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
data += current;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e("TAG", result); // this is expecting a response code to be sent from your server upon receiving the POST data
}
}

You missed () after newSendDeviceDetails. It should be like the line below:
new newSendDeviceDetails().execute(...);

Related

PHP is not receieving data from a POST request with AsyncTask

I am trying to receieve a simple string from my PHP script by using a POST request in Android Studio.
If I write for example echo "Hello"; I can receive this message in my app, but it seems like as soon as I send a POST request my webserver doesen't really get the message.
Here is how I do the POST request in my AsyncTask:
class HTTPReqTask extends AsyncTask<String, Void, String>
{
Activity activity;
OnDataSendToActivity dataSendToActivity;
Context context;
public HTTPReqTask(Context context)
{
this.context = context;
dataSendToActivity = (OnDataSendToActivity) ((Activity) context);
}
#Override
public String doInBackground(String... params)
{
HttpURLConnection urlConnection = null;
String param1 = params[0];
String line = "";
String result = "";
try
{
JsonObject postData = new JsonObject();
postData.addProperty("a", "1");
URL url = new URL(param1);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
writer.write(postData.toString());
int code = urlConnection.getResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
throw new IOException("Invalid response from server: " + code);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((line = rd.readLine()) != null)
{
result += line;
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (urlConnection != null)
{
urlConnection.disconnect();
}
}
return result;
}
#Override
protected void onPostExecute(String s)
{
try
{
if(dataSendToActivity != null)
{
Log.i("Data", s);
dataSendToActivity.sendData(s);
}
}
catch(Exception e)
{
// Nichts
}
}
}
As you can see I am using this:
JsonObject postData = new JsonObject();
postData.addProperty("a", "1");
to generate my POST request.
The postData string is: {"a":"1"}
This is my PHP script:
$post = file_get_contents("php://input");
$data = json_decode($post, true);
print_r($data);
UPDATE 1
I added now writer.flush(); (Thanks to Andy)
Now I'm getting this exception after sendung the request:
java.io.IOException: Invalid response from server: 500
So something with my PHP script is wrong.
Any suggestions?
I found now the problem.
The problem was not serversided as I expected it.
I was logging in my code some informations for the POST request and there I found this:
Log.i("LOG", urlConnection.getOutputStream().toString());
gave me this:
buffer(com.android.okhttp.internal.http.HttpConnection$ChunkedSink#843d1c8).outputStream()
So I commented this line out:
urlConnection.setChunkedStreamingMode(0);
and it works fine. I get all my data I need.
I also updated my PHP script to this:
$post = file_get_contents("php://input");
if (!empty($post))
{
$data = json_decode($post, true);
$a = $data['a'];
}
Thanks for all the help!

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.

Trouble with "inputstream" when creating mobile app that downloads weather information (with AsyncTask)

I'm trying to make a mobile app that downloads info from the openweathermap.org apis. For example, if you feed that app this link: http://api.openweathermap.org/data/2.5/weather?q=Boston,us&appid=fed33a8f8fd54814d7cbe8515a5c25d7 you will get the information about the weather in Boston, MA. My code seems to work up to the point where I have to convert the input stream to a string variable. When I do that, I get garbage. Is there a particular way to do this seemingly simple task in a proper way? Here is my code so far...
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return null;
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
TextView test = (TextView) findViewById(R.id.test);
if(result!=null) test.setText(result);
else{
Log.i(DEBUG_TAG, "returned result is null");}
}
}
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.i(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
String text = getStringFromInputStream(is);
//JSONObject json = new JSONObject(text);
//try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) {
//text = scanner.useDelimiter("\\A").next();
//}
//Bitmap bitmap = BitmapFactory.decodeStream(is);
return text;
}catch(Exception e) {
Log.i(DEBUG_TAG, e.toString());
}finally {
if (is != null) {
is.close();
}
}
return null;
}
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
Check this library . Is An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries.

android returning a JSONObject from a static method + network on main thread

I have this method which is giving a network on main thread. I want to make this api call on a separate thread using asynctask.
However, the business logic prohibits me to use non static methods. The code is:
public static JSONObject acceptOrder(String orderId, Integer loadsToAccept) throws IOException{
BufferedReader reader = null;
JSONObject resultOrder = null;
AsyncTask asyncTask = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
return null;
}
};
HttpURLConnection conn = (HttpURLConnection) new URL(GlobalConfig.getInstance().GetGoVulcanConfig().getUrl() + "/api/Order/ProcessAcceptedOrder?acceptedLoads=" + loadsToAccept + "&haulerId=" + GlobalConfig.getInstance().GetGoVulcanConfig().getHaulerId() + "&orderId=" + orderId).openConnection();
conn.setDoOutput(true);
//conn.setFixedLengthStreamingMode(jsonString.length());
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept","application/json");
InputStream inputStream = conn.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine);
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
try {
resultOrder = new JSONObject(buffer.toString());
}catch (JSONException ex){
Log.d(ex.getMessage(), "acceptOrder: ");
}
conn.disconnect();
reader.close();
return resultOrder;
}
How can I do this?
This is the form that i do to request POST or GET, I hope can help you
1) I have my class with all the request
public class RequestManager {
public static class requestPostExample extends AsyncTask<String, Void, String>{
Context context;
int exampleId;
String exampleData;
//interface to get the response in the activity
Public AsynkTaskRespone response = null;
public requestPostExample(Context context, int exampleID, String exampleData){
this.context = context;
this.exampleId = exampleID;
this.exampleData = exampleData;
}
#Override
protected String doInBackground(String... params) {
try {
String urlString = "yourUrl";
URL url = new URL(urlString);
//the variables and data you want to send by POST
String postData = "exampleID="+exampleID+"&exampleData="+exampleData;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream os = connection.getOutputStream();
os.write(postData.getBytes());
StringBuilder responseSB = new StringBuilder();
int result = connection.getResponseCode();
BufferedReader br;
// 401 - 422 - 403 - 500
if (result == 401 || result == 422 || result == 403 || result == 404 || result == 500){
br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}else {
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
}
while ( (JSON_STRING = br.readLine()) != null)
responseSB.append(JSON_STRING+ "\n");
// Close streams
br.close();
return responseSB.toString().trim();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
#Override
protected void onPostExecute(String result) {
Log.d("Result:", result);
//send the result to interface;
response.resultPostExample(result);
}
}
2) Here is the Interface
public interface AsynkTaskRespone {
void resultPostExample(String result);
}
3) Now in the activity
public class MainActivity extends AppCompatActivity implements AsynkTaskResponse {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Start Request
RequestManager.requestPostExample requestPostExample = new RequestManager.requestPostExample(this, exampleID, exampleData);
requestPostExample.response = this;
requestPostExample.execute();
}
#Override
public void resultPostExample(String result){
//here you get the result of the asynktask
}
}

Call asmx HTTP POST from android

I'm trying to post HTTP from android. If I'll request using that C# code in LINQPAD it works
void Main()
{
string r = String.Format(#"<s:Body><TrackMobileApp xmlns=""soap action url"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><device>test</device><imei>test</imei><ipAddress>127.0.0.1</ipAddress><timeStamp>2016-02-17T17:32:00.5147663+04:00</timeStamp></TrackMobileApp></s:Body>", DateTime.Now.ToString("o"));
HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create("URL.asmx");
wr.ProtocolVersion = HttpVersion.Version11;
wr.Headers.Add("SOAPAction", "soap action");
wr.Method = "POST";
wr.ContentType = "text/xml;charset=utf-8";
using (StreamWriter sw = new StreamWriter(wr.GetRequestStream()))
{
sw.Write(r);
}
HttpWebResponse rs = (HttpWebResponse)wr.GetResponse();
if (rs.StatusCode == HttpStatusCode.OK)
{
XmlDocument xd = new XmlDocument();
using (StreamReader sr = new StreamReader(rs.GetResponseStream()))
{
xd.LoadXml(sr.ReadToEnd());
xd.InnerXml.Dump();
}
}
}
But from android it gives me http 415. What's wrong?
I have this in onCreate
new DownloadTask().execute("URL.asmx");
and my methods are:
private class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//do your request in here so that you don't interrupt the UI thread
try {
return downloadContent(params[0]);
} catch (IOException e) {
return "Unable to retrieve data. URL may be invalid.";
}
}
#Override
protected void onPostExecute(String result) {
//Here you are done with the task
}
}
private String downloadContent(String myurl) throws IOException {
InputStream is = null;
int length = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestProperty("SOAPAction", "soap action");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/xml");
conn.setDoInput(true);
conn.connect();
int response = conn.getResponseCode();
Log.d(TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = convertInputStreamToString(is, length);
return contentAsString;
} finally {
if (is != null) {
is.close();
}
}
}
public String convertInputStreamToString(InputStream stream, int length) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[length];
reader.read(buffer);
return new String(buffer);
}

Categories