为此,我一直在关注Wintech的Youtube教程。我进行了所有设置,并添加了一些额外的POST方法。 GET方法工作正常,但是当我尝试POSTING位时,得到400作为响应代码。我知道这意味着语法不正确/格式错误,但是我找不到那儿。经过数小时的尝试和搜索。是的,我知道我可以在一个类和方法中完成所有操作,我这样做是为了查看引起问题的原因。全部都是。谁能告诉我哪一点可能是错误的?

MainActivity.java:

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.view.View;
import android.content.Intent;
import android.net.Uri;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.net.HttpURLConnection;
import java.net.URL;

import java.util.ArrayList;
import java.util.HashMap;
import android.os.AsyncTask;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {





@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

String choice = getIntent().getStringExtra("conNumChoice");
TextView controlNumber = (TextView) findViewById(R.id.ApptNumView);
controlNumber.setText(choice);

}


    public void openWebpage(View view){
    Uri webLink = Uri.parse("http://www.mysteelsoftware.com");
    Intent webLinkIntent = new Intent(Intent.ACTION_VIEW, webLink);

    startActivity(webLinkIntent);
    }

    public void onRefresh(View view){

    Intent backToAppt = new Intent(MainActivity.this, appointments.class);
    startActivity(backToAppt);
    }




    public void onRecInv(View view){

    }


    public void onSave(View view){

    CheckBox truckArr = (CheckBox) findViewById(R.id.truckArrivedBox);
    Boolean truckHasArrived;

    if (truckArr.isChecked()){
        truckHasArrived = true;
    }else{
        truckHasArrived = false;
    }


        new SaveConNum().execute("http://192.168.xxx.xxx/LocalAppTest/Service1.svc/SetControlNumber");
        new AddArrivalDate().execute("http://192.168.xxx.xxx/LocalAppTest/Service1.svc/AddArrivalDate");
        new AddArrivalTime().execute("http://192.168.xxx.xxx/LocalAppTest/Service1.svc/AddAr
rivalTime");

}


public void onCancel(View view){
    EditText POInput = (EditText) findViewById(R.id.PONInput);
    EditText RelNumInput = (EditText) findViewById(R.id.RelNumInput);
    EditText RailCarInput = (EditText) findViewById(R.id.RailCarInput);
    CheckBox truckArr = (CheckBox) findViewById(R.id.truckArrivedBox);
    EditText billLad = (EditText) findViewById(R.id.billNumInput);


    POInput.setText("");
    RelNumInput.setText("");
    RailCarInput.setText("");
    truckArr.setChecked(false);
    billLad.setText("");

}



class SaveConNum extends AsyncTask<String, Void, String> {

    StringBuilder sb = new StringBuilder();
    String status = null;
    Activity context;

    TextView controlNumView = (TextView) findViewById(R.id.ApptNumView);
    EditText POInput = (EditText) findViewById(R.id.PONInput);
    EditText RelNumInput = (EditText) findViewById(R.id.RelNumInput);
    EditText RailCarInput = (EditText) findViewById(R.id.RailCarInput);

    EditText billLad = (EditText) findViewById(R.id.billNumInput);
    DatePicker datepick = (DatePicker) findViewById(R.id.datePicker);
    TimePicker timepick = (TimePicker) findViewById(R.id.arrivalTimeInput);

    String conNum = controlNumView.getText().toString();
    String poNum = POInput.getText().toString();
    String relNum = RelNumInput.getText().toString();
    String railCarNum = RailCarInput.getText().toString();

    String billNum = billLad.getText().toString();
    int year = datepick.getYear();
    int month = datepick.getMonth();
    int day = datepick.getDayOfMonth();


    String date = "" + year + "" + month + "" + day + "";
    Integer dateInt = Integer.valueOf(date);


    int hour = timepick.getCurrentHour();
    int minute = timepick.getCurrentMinute();

    String time = "" + hour + "" + minute + "";




    protected void onPreExecute(){

    }
    public String doInBackground(String... connUrl){
        HttpURLConnection conn = null;
        BufferedReader reader;

        try{
            final URL url = new URL(connUrl[0]);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setChunkedStreamingMode(0);
            conn.addRequestProperty("Content-Type", "application/json;
charset=utf-8");
            conn.setRequestMethod("POST");

            JSONObject jsonObject = new JSONObject();

            jsonObject.put("conNumber", conNum);


            OutputStream out = new
BufferedOutputStream(conn.getOutputStream());
            out.write(jsonObject.toString().getBytes());
            out.flush();
            out.close();

            int result = conn.getResponseCode();
            if(result == 200){



                InputStream in = new
BufferedInputStream(conn.getInputStream());
                reader = new BufferedReader(new InputStreamReader(in));

                String line = null;

                while ((line = reader.readLine()) != null){
                    status = line;

                }

            }

        }catch(Exception ex){

        }
        return status;

    }
    public void onPostExecute(String result){
        super.onPostExecute(result);

        if(result != null){
            Toast.makeText(MainActivity.this, "Saved successfully. connum",
Toast.LENGTH_SHORT).show();

        }else{
            Toast.makeText(MainActivity.this, "Save failed. connum",
Toast.LENGTH_SHORT).show();
        }
    }
}





 class AddArrivalDate extends AsyncTask<String, Void, String> {

    StringBuilder sb = new StringBuilder();
    String status = null;
    Activity context;

    TextView controlNumView = (TextView) findViewById(R.id.ApptNumView);
    EditText POInput = (EditText) findViewById(R.id.PONInput);
    EditText RelNumInput = (EditText) findViewById(R.id.RelNumInput);
    EditText RailCarInput = (EditText) findViewById(R.id.RailCarInput);

    EditText billLad = (EditText) findViewById(R.id.billNumInput);
    DatePicker datepick = (DatePicker) findViewById(R.id.datePicker);
    TimePicker timepick = (TimePicker) findViewById(R.id.arrivalTimeInput);

    String conNum = controlNumView.getText().toString();
    String poNum = POInput.getText().toString();
    String relNum = RelNumInput.getText().toString();
    String railCarNum = RailCarInput.getText().toString();

    String billNum = billLad.getText().toString();
    int year = datepick.getYear();
    int month = datepick.getMonth();
    int day = datepick.getDayOfMonth();


    String date = "" + year + "" + month + "" + day + "";
    Integer dateInt = Integer.valueOf(date);


    int hour = timepick.getCurrentHour();
    int minute = timepick.getCurrentMinute();

    String time = "" + hour + "" + minute + "";




    protected void onPreExecute(){

    }
    public String doInBackground(String... connUrl){
        HttpURLConnection conn = null;
        BufferedReader reader;

        try{
            final URL url = new URL(connUrl[0]);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setChunkedStreamingMode(0);
            conn.addRequestProperty("Content-Type", "application/json;
charset=utf-8");
            conn.setRequestMethod("POST");

            JSONObject jsonObject = new JSONObject();

            jsonObject.put("arrivalDate", dateInt);



            OutputStream out = new
BufferedOutputStream(conn.getOutputStream());
            out.write(jsonObject.toString().getBytes());
            out.flush();
            out.close();

            int result = conn.getResponseCode();
            if(result == 200){



                InputStream in = new
BufferedInputStream(conn.getInputStream());
                reader = new BufferedReader(new InputStreamReader(in));

                String line = null;

                while ((line = reader.readLine()) != null){
                    status = line;

                }

            }

        }catch(Exception ex){

        }
        return status;

    }
    public void onPostExecute(String result){
        super.onPostExecute(result);

        if(result != null){
            Toast.makeText(MainActivity.this, "Saved successfully. date",
Toast.LENGTH_SHORT).show();

        }else{
            Toast.makeText(MainActivity.this, "Save failed. date",
Toast.LENGTH_SHORT).show();
        }
    }
}





 class AddArrivalTime extends AsyncTask<String, Void, String> {

    StringBuilder sb = new StringBuilder();
    String status = null;
    Activity context;

    TextView controlNumView = (TextView) findViewById(R.id.ApptNumView);
    EditText POInput = (EditText) findViewById(R.id.PONInput);
    EditText RelNumInput = (EditText) findViewById(R.id.RelNumInput);
    EditText RailCarInput = (EditText) findViewById(R.id.RailCarInput);

    EditText billLad = (EditText) findViewById(R.id.billNumInput);
    DatePicker datepick = (DatePicker) findViewById(R.id.datePicker);
    TimePicker timepick = (TimePicker) findViewById(R.id.arrivalTimeInput);

    String conNum = controlNumView.getText().toString();
    String poNum = POInput.getText().toString();
    String relNum = RelNumInput.getText().toString();
    String railCarNum = RailCarInput.getText().toString();

    String billNum = billLad.getText().toString();
    int year = datepick.getYear();
    int month = datepick.getMonth();
    int day = datepick.getDayOfMonth();


    String date = "" + year + "" + month + "" + day + "";
    Integer dateInt = Integer.valueOf(date);


    int hour = timepick.getCurrentHour();
    int minute = timepick.getCurrentMinute();

    String time = "" + hour + "" + minute + "";




    protected void onPreExecute(){

    }
    public String doInBackground(String... connUrl){
        HttpURLConnection conn = null;
        BufferedReader reader;

        try{
            final URL url = new URL(connUrl[0]);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setChunkedStreamingMode(0);
            conn.addRequestProperty("Content-Type", "application/json;
charset=utf-8");
            conn.setRequestMethod("POST");

            JSONObject jsonObject = new JSONObject();


            jsonObject.put("arrivalTime", time);



            OutputStream out = new
BufferedOutputStream(conn.getOutputStream());
            out.write(jsonObject.toString().getBytes());
            out.flush();
            out.close();

            int result = conn.getResponseCode();
            if(result == 200){



                InputStream in = new
BufferedInputStream(conn.getInputStream());
                reader = new BufferedReader(new InputStreamReader(in));

                String line = null;

                while ((line = reader.readLine()) != null){
                    status = line;

                }

            }

        }catch(Exception ex){

        }
        return status;

    }
    public void onPostExecute(String result){
        super.onPostExecute(result);

        if(result != null){
            Toast.makeText(MainActivity.this, "Saved successfully. time",
Toast.LENGTH_SHORT).show();

        }else{
            Toast.makeText(MainActivity.this, "Save failed. time",
Toast.LENGTH_SHORT).show();
        }
    }
}



}


WCF服务

IService1.cs

using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace WcfService2
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change
the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{


    //Get Method//
    [OperationContract]
    [WebGet(UriTemplate = "getConNum")]
    List<CONTROLNUMBER> GetConNum();

    //Get Method//
    [OperationContract]
    [WebGet(UriTemplate = "getCreDate")]
    List<CREATEDDATE> GetCreDate();

    //Post Method//
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "AddArrivalDate", BodyStyle =
WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
    int AddArrivalDate(string arrivalDate);

    //Post Method//
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "AddArrivalTime", BodyStyle =
WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
    int AddArrivalTime(string arrivalTime);

    //Post Method//
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "SetControlNumber", BodyStyle
= WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
    int SetControlNumber(int conNumber);
}
[DataContract]
public class CONTROLNUMBER
{
    string conNum;

    [DataMember]
    public string ControlNumber
    {
        get { return conNum; }
        set { conNum = value; }
    }
}
[DataContract]
public class CREATEDDATE
{
    string creDate;

    [DataMember]
    public string CreatedDate
    {
        get { return creDate; }
        set { creDate = value; }
    }

}
}


Service1.svc.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace WcfService2
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change
the class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please
select Service1.svc or Service1.svc.cs at the Solution Explorer and start
debugging.
public class Service1 : IService1
{

    //Connection String//
    private string conStr = "Data Source=xxx\\xxx;Initial
Catalog=xxxxx;User ID=xxxxx;Password=xxxxx";

    public string AddConNum(int conNum)
    {
        throw new NotImplementedException();
    }

    public List<CONTROLNUMBER> GetConNum()
    {
        List<CONTROLNUMBER> conNumList = new List<CONTROLNUMBER>();
        SqlConnection connection = new SqlConnection(this.conStr);
        connection.Open();
        SqlCommand cmd = new SqlCommand("SELECT TOP 20 CONTROLNUMBER FROM
ApptIn WHERE CREATEDBY = 'KIOSK' ORDER BY CONTROLNUMBER DESC", connection);
        cmd.CommandType = CommandType.Text;
        SqlDataReader sdr = cmd.ExecuteReader();


        while (sdr.Read())
        {



            CONTROLNUMBER conNum = new CONTROLNUMBER();
            conNum.ControlNumber = sdr["CONTROLNUMBER"].ToString();
            conNumList.Add(conNum);
        }
        return conNumList.ToList();
    }





    public List<CREATEDDATE> GetCreDate()
    {
        List<CREATEDDATE> creDateList = new List<CREATEDDATE>();
        SqlConnection connection = new SqlConnection(this.conStr);
        connection.Open();
        SqlCommand cmd = new SqlCommand("SELECT TOP 20
dbo.CLADate(CREATEDDATE) CREATEDDATE FROM ApptIn WHERE CREATEDBY = 'KIOSK'
ORDER BY CONTROLNUMBER DESC", connection);
        cmd.CommandType = CommandType.Text;
        SqlDataReader sdr = cmd.ExecuteReader();


        while (sdr.Read())
        {



            CREATEDDATE creDate = new CREATEDDATE();
            creDate.CreatedDate = sdr["CREATEDDATE"].ToString();
            creDateList.Add(creDate);

        }
        return creDateList.ToList();
    }

    public int AddArrivalDate(string arrivalDate)
    {
        int status = 0;
        SqlConnection connection = new SqlConnection(this.conStr);
        SqlCommand cmd = new SqlCommand();
        try
        {

            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
            cmd = new SqlCommand("INSERT INTO ApptIn (ARRIVALDATE,
 ARRIVALTIME) VALUES (@ArrivalDate, @ArrivalTime)", connection);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@ArrivalDate", arrivalDate);


            cmd.ExecuteReader();
            status = 1;
        }
        catch(Exception ex)
        {
            throw ex;
        }
        finally
        {
            connection.Close();
            cmd.Dispose();
        }
        return status;
    }




    public int AddArrivalTime(string arrivalTime)
    {
        int status = 0;
        SqlConnection connection = new SqlConnection(this.conStr);
        SqlCommand cmd = new SqlCommand();
        try
        {

            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
            cmd = new SqlCommand("INSERT INTO ApptIn (ARRIVALTIME) VALUES
(@ArrivalTime)", connection);
            cmd.CommandType = CommandType.Text;

            cmd.Parameters.AddWithValue("@ArrivalTime", arrivalTime);

            cmd.ExecuteReader();
            status = 1;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            connection.Close();
            cmd.Dispose();
        }
        return status;
    }



    public int SetConNum(int conNumber)
    {
        int status = 0;
        SqlConnection connection = new SqlConnection(this.conStr);
        SqlCommand cmd = new SqlCommand();
        try
        {

            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
            cmd = new SqlCommand("INSERT INTO ApptIn (CONTROLNUMBER) VALUES
 (@ConNum)", connection);
            cmd.CommandType = CommandType.Text;

            cmd.Parameters.AddWithValue("@ConNum", conNumber);
            cmd.ExecuteReader();
            status = 1;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            connection.Close();
            cmd.Dispose();
        }
        return status;
    }

    public int SetControlNumber(int conNumber)
    {
        throw new NotImplementedException();
    }
  }
  }


当我尝试在浏览器中查看它时,我得到java - 在Android Studio中从POST获取400的响应代码-LMLPHP
让我知道我是否提供了足够的信息。

最佳答案

我知道那会很愚蠢。我需要Web服务中的UPDATE sql命令,而不是INSERT。

08-26 21:52