I have a server made in python that reads the querystring-message and stores it in a sqlite database, and then displays the content.
Now I want to send the message from a android application. This is my code so far.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Button send;
TextView display;
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send = (Button)findViewById(R.id.button1);
display = (TextView)findViewById(R.id.editText1);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
post();
}
catch(Exception e)
{
display.setText("Det sket sig");
}
}
public void post() throws UnsupportedEncodingException
{
message = display.getText().toString();
String data = URLEncoder.encode("?message", "UTF-8")
+ "=" + URLEncoder.encode(message, "UTF-8");
String text = "";
BufferedReader reader=null;
try
{
URL url = new URL("http:homepage.net");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
text = sb.toString();
}
catch(Exception e)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
display.setText(text);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is not functioning as per the expectations. What am i doing wrong here?
for network related operation you have to use asynctask or thread other wise you wil get NetworkOnMainThread Exception.
refer here
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
Use following AsyncTask to make server request:
public class RestServiceTask extends AsyncTask<String, Void, String> {
private String errorMessage;
public RestServiceTask() {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String url = params[1];
String method = params[2];
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 60000);
HttpConnectionParams.setSoTimeout(httpParameters, 60000);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpUriRequest request;
try {
if (method.equals("get")) {
request = new HttpGet(url);
} else {
request = new HttpPost(url);
if (params.length > 0 && params[0] != null) {
StringEntity entity = new StringEntity(params[0]);
((HttpPost) request).setEntity(entity);
Crashlytics.log(Log.INFO, "Request", params[0]);
}
((HttpPost) request).setHeader("Content-Type",
"application/json");
}
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String json = convertStreamToString(entity.getContent());
Crashlytics.log(Log.INFO, "Response", json);
return json;
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//process your result
}
public String convertStreamToString(InputStream is) throws IOException {
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
} else {
return "";
}
}
}
Use it by:
new RestServiceTask().execute("<json string>",url,method);//method can be get,post
try this simple example if you have any doubt follow this links:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.codeincloud.tk/First.php");
try {
HttpResponse response = httpclient.execute(httppost);
final String str = EntityUtils.toString(response.getEntity());
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(str);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
http://codeoncloud.blogspot.in/2012/07/android-php-web-service-client.html,http://sampleprogramz.com/android/singlewebservicecall.php
You should change the title of your question, there is no such thing as queryString in a POST. Query String parameters only gets added in a GET, and in POST you pass data in the body of the request.
Also, you could use this in combination with AsyncTask to solve your problem
EDIT: Also, Check here for more about GET and POST
Try this :
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost(your website);
List<NameValuePair> entityParams = new ArrayList<NameValuePair>();
entityParams.add(new BasicNameValuePair("action", "postcomment"));
entityParams.add(new BasicNameValuePair("app_id", com.appbuilder.sdk.android.Statics.appId));
entityParams.add(new BasicNameValuePair("message", message1));
entityParams.add(new BasicNameValuePair("message2", message2));
httpPost.setEntity(new UrlEncodedFormEntity(entityParams, "utf-8"));
String resp = httpClient.execute(httpPost, new BasicResponseHandler());
Related
Since org.appache is deprecated in Android 5.1.1 , and they suggest to use HttpUrlConnection .
Could you help me to change my code this , with valid HttUrlConnection command (im new in Android)
package com.example.cbmedandroid;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.43.13:8000/api/horaire.json");
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
Thanks
Also , getASCIIContentFromEntity(HttpEntity entity) seems to be deprecated to !
EDIT : This is what i have changed in my code .
protected String doInBackground(Void... params) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://192.168.43.13:8000/api/horaire.json");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
But what about the "LongRunningGetIO extends AsyncTask " method ?
a HttpGet request without setting anything (like an Accept: application/json header, choosing an encoding, ...) should be fairly equivalent to this:
#Override
protected String doInBackground(Void... params) {
return get("http://192.168.43.13:8000/api/horaire.json");
}
private String get(String urlString) {
try {
HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlString).openConnection();
Reader reader = new InputStreamReader(urlConnection.getInputStream());
try {
StringWriter writer = new StringWriter();
char[] cbuf = new char[8192];
int read;
while ((read = reader.read(cbuf)) != -1) {
writer.write(cbuf, 0, read);
}
return writer.toString();
} finally {
reader.close();
}
} catch (Exception e) {
return e.getMessage();
}
}
Try This
#Override
protected String doInBackground(Void... params) {
StringBuffer response_string = new StringBuffer();
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestMethod("POST");
OutputStream os = con.getOutputStream();
os.write(params.toString().getBytes("UTF-8"));
os.close();
int responseCode = con.getResponseCode();
System.out.println("PostParseURL "+url);
System.out.println("PostParseCODE " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response_string.append(inputLine);
}
in.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response_string.toString();
}
and yes there are no need to getASCIIContentFromEntity method and here params are the Your JSONObject request
Hi, i don't undestand why this doesn't work, i am trying to retrieve whatever comes after "offer" in the specified url and then display it but when i click on the Offer button on android screen nothing happens. Please help if you could. I have the internet permission in manifest.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
public class LoggedIn extends Activity {
AlertDialog alertDialogStores;
ObjectItem[] ObjectItemData = new ObjectItem[5];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logged_in);
// a button to show the pop up with a list view
View.OnClickListener handler = new View.OnClickListener(){
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonShowPopUp:
LoaderTask task = new LoaderTask();
task.execute();
break;
}
}
};
findViewById(R.id.buttonShowPopUp).setOnClickListener(handler);
}
class LoaderTask extends AsyncTask<Void , Void ,String>{
ProgressDialog progressDialog ;
public LoaderTask(){
progressDialog = new ProgressDialog(SplashActivity.this);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.setMessage("Loading app data...");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
return connect("http://ec2-54-175-18-179.compute-1.amazonaws.com/customers/37.json");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
showPopUp(result);
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public String connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
//Log.i(TAG,response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
instream.close();
return result;
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
public void showPopUp(String result){
try{
JSONArray jsonArray = new JSONArray(result);
for(int i = 0 ; i <= 5 ; i++){
JSONObject o = jsonArray.getJSONObject(i);
String http_response = o.getString("offer");
System.out.println("test "+http_response);
//ObjectItemData[i] = new ObjectItem(o);
ObjectItemData[0] = new ObjectItem(http_response);
ObjectItemData[1] = new ObjectItem(http_response);
ObjectItemData[2] = new ObjectItem(http_response);
ObjectItemData[3] = new ObjectItem(http_response);
ObjectItemData[4] = new ObjectItem(http_response);
// adapter instance
ArrayAdapterItem adapter = new ArrayAdapterItem(this, R.layout.list_view_row_item, ObjectItemData);
// create a new ListView, set the adapter and item click listener
ListView listViewItems = new ListView(this);
listViewItems.setAdapter(adapter);
listViewItems.setOnItemClickListener(new OnItemClickListenerListViewItem());
// put the ListView in the pop up
alertDialogStores = new AlertDialog.Builder(LoggedIn.this)
.setView(listViewItems)
.setTitle("Offers")
.show();
}
} catch(Exception e){e.printStackTrace();}
finally{System.out.println("Success");
}
}
}
class LoaderTask extends AsyncTask<Void , Void ,String>{
ProgressDialog progressDialog ;
public LoaderTask(){
progressDialog = new ProgressDialog(SplashActivity.this);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.setMessage("Loading app data...");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
return connect("http://ec2-54-175-18-179.compute-1.amazonaws.com/customers/37.json");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
showPopUp(result);
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public String connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
//Log.i(TAG,response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
instream.close();
return result;
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
public void showPopUp(String result){
try{
JSONArray jsonArray = new JSONArray(result);
for(int i = 0 ; i < jsonArray.length() ; i++){
JSONObject o = jsonArray.getJSONObject(i);
String http_response = o.getString("offer");
System.out.println("test "+http_response);
ObjectItemData[i] = new ObjectItem(http_response);
}
//and populate your listview here
} catch(Exception e){e.printStackTrace();}
finally{System.out.println("Success");
}
}
and call this to do task
new LoaderTask().execute();
I created two activities one contains some text fields which accepts data. From other activity(Async Task) this data is sent to the server and gets the response from the server.
I am able to log the response but unable to store that response in variable and user in other activities. Is there any way to do that?
Here is one activity,
RegisterDevice.java
package sys.darpan.tracking;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class RegisterDevice extends Activity{
EditText regEmail, regPassword, regImei, regDeviceName, regVehicleNumber;
Button regButton;
AsyncRegisterDevice asd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_device);
regEmail = (EditText)findViewById(R.id.regEmail);
regPassword = (EditText)findViewById(R.id.regPassword);
regVehicleNumber = (EditText)findViewById(R.id.regVehicleNum);
regImei = (EditText)findViewById(R.id.regImei);
regDeviceName = (EditText)findViewById(R.id.regDeviceName);
regButton = (Button)findViewById(R.id.regButton);
regImei.setText("165465416416416");
regDeviceName.setText("GT-I9300");
regButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerDevice();
}
});
}
protected void registerDevice(){
asd = new AsyncRegisterDevice();
String email = regEmail.getText().toString();
String password = regPassword.getText().toString();
String imei = regImei.getText().toString();
String deviceName = regDeviceName.getText().toString();
String vehicleNo = regVehicleNumber.getText().toString();
String aobj[] = new String[5];
aobj[0] = email;
aobj[1] = password;
aobj[2] = vehicleNo;
aobj[3] = imei;
aobj[4] = deviceName;
asd.execute(aobj);
}
}
Here is Async Task,
package sys.darpan.tracking;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.util.Log;
public class AsyncRegisterDevice extends AsyncTask<String, String, String> {
String sb;
String finalResult;
#Override
protected String doInBackground(String... params) {
String email = params[0];
String password = params[1];
String vnumber = params[2];
String imei = params[3];
String deviceName = params[4];
DefaultHttpClient defaulthttpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://logicvibes.com/vts/register-device.php");
ArrayList<BasicNameValuePair> arraylist = new ArrayList<BasicNameValuePair>(5);
arraylist.add(new BasicNameValuePair("email", email));
arraylist.add(new BasicNameValuePair("pass", password));
arraylist.add(new BasicNameValuePair("vno", vnumber));
arraylist.add(new BasicNameValuePair("imei", imei));
arraylist.add(new BasicNameValuePair("dname", deviceName));
try
{
httppost.setEntity(new UrlEncodedFormEntity(arraylist));
httppost.getAllHeaders();
}
catch (UnsupportedEncodingException unsupportedencodingexception)
{
unsupportedencodingexception.printStackTrace();
}
try {
// HttpResponse is an interface just like HttpPost.
//Therefore we can't initialize them
HttpResponse httpResponse = defaulthttpclient.execute(httppost);
// According to the JAVA API, InputStream constructor do nothing.
//So we can't initialize InputStream although it is not an interface
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
sb = stringBuilder.toString();
Log.d("Custom resp: ", sb);
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String sb) {
Log.d("RESULT", "Result : " + sb);//this returns NULL
finalResult = sb;
}
public String getFinalResult() {
return finalResult;
}
}
I searched a lot but no luck, please tell me the proper way to do this.
Solved it by using,
try {
asd.execute(aobj).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
The main thread waits until the async task finished processing. (good for short processes)
I want to make an Android app that reads some data from a php page and put it into a textview.
I already tested it yesterday and it worked! but I dont know what i changed so today it wont work..
(I am sure that I dont used async tasks or something like this)
package com.example.test04;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private String url = "this is the url ";
private TextView textView;
private Thread thread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById (R.id.textView2);
// runthread();
try{
textView.setText("");
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
String line ="";
while ((line = rd.readLine()) != null) {
line = line.replace("\\n", "\n");
textView.append(line);
}
} catch (Exception e) {
Log.e("log_tag1234", "Error converting result === " + e.toString());
}
}}
after that I tried it with runOnUiThread but it also dont works
//
// private void runThread() {
//
// new Thread() {
// public void run() {
//
// try {
// runOnUiThread(new Runnable() {
//
// #Override
// public void run() {
// try{
// textView.setText("");
// HttpClient client = new DefaultHttpClient();
// HttpGet request = new HttpGet(url);
// HttpResponse response = client.execute(request);
//
// BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
//
// String line ="";
// while ((line = rd.readLine()) != null) {
// line = line.replace("\\n", "\n");
// textView.append(line);
//
// }
//
// } catch (Exception e) {
// Log.e("log_tag1234", "Error converting result === " + e.toString());
// }
// }
// });
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// }
// }.start();
// }
how can I fix it as easy as possible? why it doesnt work anymore?
I am doing an Android program that is supposed to send data from the tablet to a PHP Web Service. The code for sending the JSON:
package com.example.shvalidation;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
public class MainMenuScreen extends Activity {
//JSON Variables
JSONParser jsonParser = new JSONParser();
String pid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu_layout);
new TestThread().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu_layout, menu);
return true;
}
public void PlantToDome(View view) {
Intent intent = new Intent(this, SelectLocationScreen.class);
startActivity(intent);
}
//Código del Web Service
public class TestThread extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(MainMenuScreen.this, "Loading", "Loading data, please wait..");
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
protected Void doInBackground(Void...args0) {
try {
HttpClient client = new DefaultHttpClient();
HttpResponse response;
HttpPost post = new HttpPost("http://192.168.1.101:8080/GetBook.php");
JSONObject holder = new JSONObject();
JSONObject euid = new JSONObject();
euid.put("euid", 1);
holder.accumulate("euids", euid);
euid.put("euid", 2);
holder.accumulate("euids", euid);
post.setHeader("json", holder.toString());
StringEntity se = new StringEntity(holder.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
Log.i("Read from Server", a);
}
} catch (Exception e) {
Log.d("error", e.toString());
}
return null;
}
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}
}
The PHP Web Service:
<?php
ob_start();
var_dump(json_decode(file_get_contents('php://input')));
$out = ob_get_contents();
ob_end_clean();
$f = fopen('out.txt', 'w+');
fwrite($f, html_entity_decode($out));
fclose($f);
?>
I have tried different methods for getting the JSON, but none of them have worked for me. Maybe the fine people of StackOverflow can help me out with this, as they always have for every other problem that I've had.
From the comments section, it appears you only want the JSON being sent to your PHP script. Normally, you post POST this to PHP, and extract it:
<?php
print_r($_POST);
$json_string = $_POST['message'];
$json = json_decode($json_string);
print_r($json);
?>
And then a small client example:
public static void main(String[] args) {
String json = "{\"message\":\"This is a message\"}";
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost("http://somesite.com/test.php");
StringEntity params =new StringEntity("message=" + json);
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
// handle response here...
System.out.println(org.apache.http.util.EntityUtils.toString(response.getEntity()));
org.apache.http.util.EntityUtils.consume(response.getEntity());
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown();
}
}
The output of this is:
Array
(
[message] => {"message":"This is a message"}
)
stdClass Object
(
[message] => This is a message
)