我正在制作一个应用程序,在那个应用程序中,我需要将数据发送到php服务器并在php服务器上接收数据,反之亦然。我无法将数据从Android应用程序发送到php服务器?你能告诉我怎么做吗?
这是我向服务器发送数据的代码
public class EventServiceHandler
{
String data;
DoSomething d = new DoSomething();
public EventServiceHandler() {
// TODO Auto-generated constructor stub
d.execute();
}
public void getObject()
{
String s = "http://www.example.com/thisisthis.php";
try {
URL url = new URL(s);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setConnectTimeout(100000);
connection.setReadTimeout(100000);
connection.connect();
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
response=connection.getResponseCode();
String name="sateesh";
String testing=URLEncoder.encode("name", "utf-8")
+ "=" + URLEncoder.encode(name, "utf-8");
out.write(testing);
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class DoSomething extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... params)
{
// TODO Auto-generated method stub
getObject();
return null;
}
}
}
这是php服务器上用于在服务器上接收数据的代码。
<?php
if($_POST)
{
$name = urldecode($_POST['name']);
echo $name;
error_log($name,0);
echo " ok";
}
else if(is_null($_POST) OR empty($_POST))
{
error_log("empty or null",0);
echo "in else if";
}
else
{
echo "<br>";
echo "in else";
}
echo "just";
&GT;
我如何知道我正在接收数据,以及如何确保收到数据 我是php新手,从未在android中使用过http类 提前谢谢。
答案 0 :(得分:1)
将此JSONParser.java文件复制并粘贴到您的src文件夹
中在您的android项目活动中编写以下代码。
public class CreateDailyReports extends Activity实现OnClickListener {
EditText edRTitle,edRDesc;
Button btnCreateReport;
String userId,cmid;
private ProgressDialog pdialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
int success=0;
private static String url_create_daily_reports = "";
private static String url_send_message = "";
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_daily_reports);
initializeControls();
btnCreateReport.setOnClickListener(this);
}
public void initializeControls(){
edRTitle = (EditText)findViewById(R.id.editTextOfReportTitle);
edRDesc = (EditText)findViewById(R.id.editTextOfReportDescription);
btnCreateReport = (Button)findViewById(R.id.buttonOfCreateReport);
}
public class CreateDReports extends AsyncTask<String,String,String>
{
@Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pdialog = new ProgressDialog(CreateDailyReports.this);
pdialog.setMessage("Wait... ");
pdialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
pdialog.setIndeterminate(false);
pdialog.setCancelable(false);
pdialog.show();
}
@Override
protected String doInBackground(String... args)
{
String empid = userId;
String sRtitle = edRTitle.getText().toString();
String sRdesc = edRDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("eid",empid));
params.add(new BasicNameValuePair("rtitle",sRtitle));
params.add(new BasicNameValuePair("rdesc",sRdesc));
params.add(new BasicNameValuePair("cid",cmid));
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(url_create_daily_reports, "POST", params);
//Log.i("login", json.toString());
try
{
// Checking for SUCCESS TAG
success = json.getInt("success");
}
catch (JSONException e)
{
// TODO: handle exception
e.printStackTrace();
}
return null;
} // doinbackground ends
@Override
protected void onPostExecute(String file_url)
{
pdialog.dismiss();
if(success==1){
Toast myToast = Toast.makeText(CreateDailyReports.this, "Your Report has been Created", 10);
myToast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
myToast.show();
new SendDailyReports().execute();
}
else
{
Toast myToast = Toast.makeText(CreateDailyReports.this, "Your Reprot has not been Created", 10);
myToast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
myToast.show();
}
}
} // update status of product auction over
@Override
public void onClick(View v) {
int id = v.getId();
if(id==btnCreateReport.getId()){
new CreateDReports().execute();
}
}
} 3. php脚本
<?php
$ value1 = $ _REQUEST [&#34; rtitle&#34;]; $ value2 = $ _REQUEST [&#34; rdesc&#34;];
// connect to your database
$result = mysql_query(" insert into table(field1,field2) values('$value1','$value2' )" );
if($result == 1)
{
// successfully inserted
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
}
else
{
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
&GT;