java.io.IOException:HTTP请求失败,HTTP状态:ANDROID STUDIO中的400

时间:2017-11-06 05:16:00

标签: android sql-server visual-studio soap

这是此链接的延续:

java.net.SocketException: Permission denied in Android Studio with Visual Studio 2017 Web Service

我在Android Studio中使用KSOAP2库,在SQL SERVER中使用" Clientes" Visual Studio 2017中的表和Web服务ASP.NET。

AndroidManifest:

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ruper.serviciosweb_soap_rest">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

我的MainActivity类:

package com.example.ruper.serviciosweb_soap_rest;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

public class MainActivity extends AppCompatActivity {
    EditText etxtNombre, etxtTelefono;
    Button btnEnviar, btnConsultar;
    ListView lstClientes;
    TextView tviewResultado;


String NAMESPACE="ruperdevcoder";
String URL="http://10.0.2.2:51629/ServicioClientes.asmx";
String METHOD_NAME="NuevoClienteSimple";
String SOAP_ACTION="ruperdevcoder/NuevoClienteSimple";

private static final int MY_PERMISSIONS_REQUEST_INTERNET=1;

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

    etxtNombre = (EditText)findViewById(R.id.etxtNombre);
    etxtTelefono = (EditText)findViewById(R.id.etxtTelefono);
    btnEnviar = (Button)findViewById(R.id.btnEnviar);
    btnConsultar = (Button)findViewById(R.id.btnConsultar);
    tviewResultado = (TextView)findViewById(R.id.tviewResultado);
    lstClientes = (ListView)findViewById(R.id.lstClientes);
    int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET);
    if(permissionCheck!= PackageManager.PERMISSION_GRANTED){
        if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.INTERNET)){
        }else{
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.INTERNET
            },MY_PERMISSIONS_REQUEST_INTERNET);
        }
    }

    btnConsultar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TareaWSConsulta tarea = new TareaWSConsulta();
            tarea.execute();
        }
    });

    btnEnviar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TareaWSEnviar tarea = new TareaWSEnviar();
            tarea.execute(etxtNombre.getText().toString(),etxtTelefono.getText().toString());
        }
    });

}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[],int[]grantResults){
    switch(requestCode){
        case MY_PERMISSIONS_REQUEST_INTERNET:{
            if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
            }else{
            }
            return;
        }

    }
}

private class TareaWSConsulta extends AsyncTask<String,Integer,Boolean> {

    private Cliente[] listaClientes;

    @Override
    protected Boolean doInBackground(String... params) {
        Boolean result=true;

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);

        HttpTransportSE transporte = new HttpTransportSE(URL);


        try{
            transporte.call(SOAP_ACTION, envelope);

            SoapObject resSoap=(SoapObject)envelope.getResponse();
            listaClientes = new Cliente[resSoap.getPropertyCount()];

            for(int i=0; i<listaClientes.length;i++){
                SoapObject ic = (SoapObject) resSoap.getProperty(i);

                Cliente cli = new Cliente();
                cli.id=Integer.parseInt(ic.getProperty(0).toString());
                cli.nombre=ic.getProperty(1).toString();
                cli.telefono=Integer.parseInt(ic.getProperty(2).toString());
                listaClientes[i]=cli;
            }

        }catch(Exception e) {
            Log.e("CONSULTA", e.toString());
            result = false;
        }
        return result;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Boolean result) {

        if(result){
            final String[] datos = new String[listaClientes.length];
            for(int i=0;i<listaClientes.length;i++){

                datos[i]=listaClientes[i].nombre;
                ArrayAdapter<String> adaptador = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, datos);

                lstClientes.setAdapter(adaptador);
            }
        }else{
            tviewResultado.setText("Error!");
        }
    }
}
private class TareaWSEnviar extends AsyncTask<String,Integer,Boolean>{
    public TareaWSEnviar() {
        super();
    }

    @Override
    protected Boolean doInBackground(String... params) {
        boolean result=true;

        String nombre= params[0];
        String telefono= params[1];

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        request.addProperty("nombre", nombre);
        request.addProperty("telefono", telefono);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet=true;
        envelope.setOutputSoapObject(request);
        HttpTransportSE transporte = new HttpTransportSE(URL);

        try{
            transporte.call(SOAP_ACTION, envelope);
            SoapPrimitive resultado_xml= (SoapPrimitive)envelope.getResponse();
            String res=resultado_xml.toString();
            if(!res.equals(1)){
                result=false;
            }

        }catch(Exception e){
            Log.e("ENVIAR",e.toString());
            result = false;
        }
        return result;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if(result){
            tviewResultado.setText("INSERTADO OK!");
        }else{
            tviewResultado.setText("ERROR!");
        }
    }
}
}

执行&#34; TareaWSConsulta&#34;时出现下一个错误:

java.io.IOException: HTTP request failed, HTTP status: 400

NAMESPACE,URL,METHOD_NAME和SOAP_ACTION是正确的...知道问题应该是什么?谢谢!

2 个答案:

答案 0 :(得分:0)

transporte.call(SOAP_ACTION, envelope);// error here 
SOAPAction: "http://tempuri.org/UpdateNotificationToken" // soap action like that and you using 
 String SOAP_ACTION="ruperdevcoder/NuevoClienteSimple"; //change this 

您可以从asmx文件中获取soap操作

    POST /Services/apk_Driver.asmx HTTP/1.1
Host: redrive.orataro.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
 SOAPAction: "http://tempuri.org/UpdateNotificationToken"

     <?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
      <soap:Body>
        <UpdateNotificationToken xmlns="http://tempuri.org/">
          <DriverID>string</DriverID>
          <CompanyID>string</CompanyID>
          <NotificationToken>string</NotificationToken>
          <DeviceType>string</DeviceType>
        </UpdateNotificationToken>
      </soap:Body>
    </soap:Envelope>

答案 1 :(得分:0)

My NAMESPACE是“ruperdevcoder”,WebMethod的SOAPACTION是“ruperdevcoder / ListadoClientes”:

POST /ServicioClientes.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "ruperdevcoder/ListadoClientes"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <ListadoClientes xmlns="ruperdevcoder" />
  </soap:Body>
</soap:Envelope>
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <ListadoClientesResponse xmlns="ruperdevcoder">
      <ListadoClientesResult>
        <Cliente>
          <Id>int</Id>
          <Nombre>string</Nombre>
          <Telefono>int</Telefono>
        </Cliente>
        <Cliente>
          <Id>int</Id>
          <Nombre>string</Nombre>
          <Telefono>int</Telefono>
        </Cliente>
      </ListadoClientesResult>
    </ListadoClientesResponse>
  </soap:Body>
</soap:Envelope>

我在VisualStudio 2017中的.asmx.cs文件:

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;

namespace ServicioWebSoap
{
    [WebService(Namespace = "ruperdevcoder")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class ServicioClientes : System.Web.Services.WebService
    {

        [WebMethod]
        public int NuevoClienteSimple(string nombre, int telefono) {
            SqlConnection con = new SqlConnection(@"Data Source = (localdb)\ServidorLocal; Initial Catalog=DBCLIENTES;Integrated Security=True");
            con.Open();

            string sql = "INSERT INTO Clientes(Nombre, Telefono) VALUES (@nombre, @telefono)";

            SqlCommand cmd = new SqlCommand(sql, con);

            cmd.Parameters.Add("@nombre", SqlDbType.NVarChar).Value = nombre;
            cmd.Parameters.Add("@telefono", SqlDbType.Int).Value = telefono;

            int res = cmd.ExecuteNonQuery();

            con.Close();

            return res;
        }

        [WebMethod]
        public Cliente[] ListadoClientes(){

            SqlConnection con = new SqlConnection(@"Data Source=(localdb)\ServidorLocal;Initial Catalog=DBCLIENTES;Integrated Security=True");
            con.Open();

            string sql = "SELECT IdCliente, Nombre, Telefono FROM Clientes";

            SqlCommand cmd = new SqlCommand(sql, con);
            SqlDataReader reader = cmd.ExecuteReader();

            List<Cliente> lista = new List<Cliente>();

            while (reader.Read()) {
                lista.Add(new Cliente(reader.GetInt32(0), reader.GetString(1), reader.GetInt32(2)));
            }
            con.Close();

            return lista.ToArray();
        }

        [WebMethod]
        public int NuevoClienteObjeto(Cliente cliente) {
            SqlConnection con = new SqlConnection(@"Data Source=(localdb)\ServidorLocal; Initial Catalog=DBCLIENTES;Integrated Security=True");
            con.Open();

            string sql = "INSERT INTO Clientes(Nombre, Telefono) VALUES (@nombre,@telefono)";
            SqlCommand cmd = new SqlCommand(sql, con);

            cmd.Parameters.Add("@nombre", SqlDbType.NVarChar).Value = cliente.Nombre;
            cmd.Parameters.Add("@telefono", SqlDbType.Int).Value = cliente.Telefono;

            int res = cmd.ExecuteNonQuery();

            con.Close();
            return res;
        }

    }
}