Вызов .NET Web API Post Service в Android отправляет нулевое сообщение - PullRequest
0 голосов
/ 03 декабря 2018

Я реализовал службу Web API на стороне ASP.net и хотел вызвать ее с Android, но отправленное сообщение имеет значение null "type has been uploaded successfully: !".Отправленные данные должны быть напечатаны между двоеточием и восклицательным знаком.Я также проверил БД, тип с нулевым значением был добавлен.Я также проверил Web API на Fiddler, и он работает правильно, когда я отправляю строковое значение.Так как я могу правильно отправить данные?Заранее спасибо.

Сторона ASP.net

[HttpPost]
    public String SetType([FromBody]string type)
    {
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MConnectionString"].ConnectionString);
        try
        {
            connection.Open();
            SqlCommand cmd = new SqlCommand("insert into [MeasureType] (type_name) values (' " + type + " ')", connection);
            cmd.ExecuteNonQuery();

            return "type has been uploaded successfully : " + type + " !";
        }
        catch (Exception exception)
        {
            return exception.Message + "error uploading type";
        }
        finally
        {
            connection.Close();
        }

    }

На стороне Android

public String SetMeasureType(String type)
{
    java.net.URL url = null;
    StringBuilder builder = new StringBuilder();
    HttpURLConnection connection = null;
    try {
        url = new URL("http://192.168.1.140:65079/api/monitoringtool/SetType");
        // open a connection
        connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true); // to get request only
        connection.setDoOutput(true); // upload a request body
        connection.setUseCaches(false);
        connection.setRequestMethod("POST"); // request method post
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Content-Length","" + Integer.toString(type.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");
        connection.setConnectTimeout(3000); // connection time out
        connection.setReadTimeout(3000); // read time out

        // Send request
        OutputStream outStream = new BufferedOutputStream(connection.getOutputStream());
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outStream, "UTF-8"));
        writer.write(type);
        writer.flush();
        writer.close();
        outStream.close();

        // get response
        InputStream inStream = connection.getInputStream(); // input stream of connection to get data
        BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)); // reader for reading data from stream
        String line;
        while((line = reader.readLine()) != null)
        {
            builder.append(line);
        }
        int responseCode = connection.getResponseCode();
        reader.close();
        if(responseCode == HttpURLConnection.HTTP_OK)
        {
            return builder.toString();
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return builder.toString();
}

1 Ответ

0 голосов
/ 03 декабря 2018

Две вещи,

На стороне Android отправьте фактическую строку JSON

//...

//construct JSON
String json = "{\"type\":\"" + type + "\"}";
connection.setRequestProperty("Content-Length","" + Integer.toString(json.getBytes().length));
//send 
writer.write(json);

//...

На стороне веб-API ASP.net

создайте модель для представленияданные, которые будут получены

public class TypeModel {
    public string type { get; set; }
}

И обновите действие ApiController, чтобы ожидать модель

[HttpPost]
public IHttpActionResult SetType([FromBody]TypeModel model) {

    if (!ModelState.IsValid) return BadRequest(ModelState);

    var connectionString = ConfigurationManager.ConnectionStrings["MConnectionString"].ConnectionString;
    using (var connection = new SqlConnection(connectionString)) {
        try {
            var type = model.type;
            connection.Open();
            var cmd = new SqlCommand("insert into [MeasureType] (type_name) values (@type)", connection);

            var parameter = cmd.CreateParameter();
            parameter.ParameterName = "@type";
            parameter.Value = type;

            cmd.Parameters.Add(parameter);

            return Ok("type has been uploaded successfully : " + type + " !");
        } catch (Exception exception) {
            return InternalServerError(exception);
        }
    }
}

Также обратите внимание на использование параметров, чтобы избежать внедрения SQL.

...