0

这是客户端 Android MainActivity.java文件:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
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.JSONException;
import org.json.JSONStringer;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.e("oncreate ", "girdi");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText username = (EditText) findViewById(R.id.usernameEditText);

        final EditText password = (EditText) findViewById(R.id.passwordEditText);
        Button sendBtn = (Button) findViewById(R.id.sendBtn);

        sendBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
            HttpPost request = new HttpPost("http://10.0.2.2:8732/Design_Time_Addresses/MyWCFSolution/Service1/Check");
            request.setHeader("Accept", "application/json");
            request.setHeader("Content-type", "application/json");

            // Build JSON string
            JSONStringer userJson=null;
            try {
                userJson = new JSONStringer()
                    .object()
                       .key("user")
                          .object()
                         .key("Username").value(username.getText().toString())                                                                                                                                                        
                         .key("Password").value(password.getText().toString())                                                     
                         .key("Name").value(password.getText().toString())
                          .endObject()
                       .endObject();
                Log.e("json", "json created");
            } catch (JSONException e) {

                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            StringEntity entity=null;
            try {
                entity = new StringEntity(userJson.toString(),"UTF-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                                                
            entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            entity.setContentType("application/json");

            request.setEntity(entity);

            // Send request to WCF service
            DefaultHttpClient httpClient = new DefaultHttpClient();


            try {
                Log.e("response", "connect");
                HttpResponse response = httpClient.execute(request);

                Log.e("response","response get"+response.toString());
                //System.out.println(response.toString());


                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                String json = reader.readLine();

                Log.e("json string","test "+json.toString()+" lazım");
                System.out.println(json);
                //JSONTokener tokener = new JSONTokener(json);
                //JSONArray finalResult = new JSONArray(tokener);


            }catch (Exception e){
                e.printStackTrace();
            }
        }

    });

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

服务器端:

应用程序配置:

        <?xml version="1.0"?>
        <configuration>

          <appSettings>
            <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
          </appSettings>
          <system.web>
            <compilation debug="true"/>
          </system.web>
          <!-- When deploying the service library project, the content of the config file must be added to the host's 
          app.config file. System.Configuration does not support config files for libraries. -->
          <system.serviceModel>
             <services>
                 <service name="MyWCFSolution.Service1">
                     <endpoint address="" binding="wsHttpBinding" contract="MyWCFSolution.IService1">
                          <identity>
                              <dns value="localhost"/>
                          </identity>
                      </endpoint>
                      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
                      <host>
                          <baseAddresses>
                              <add baseAddress="http://localhost:8732/Design_Time_Addresses/MyWCFSolution/Service1/"/>
                          </baseAddresses>
                      </host>
                 </service>
             </services>
             <behaviors>
                 <serviceBehaviors>
                      <behavior>
<!-- To avoid disclosing metadata information, 
set the value below to false and remove the metadata endpoint above before deployment -->
                          <serviceMetadata httpGetEnabled="True"/>
<!-- To receive exception details in faults for debugging purposes, 
set the value below to true. Set to false before deployment 
to avoid disclosing exception information -->
                          <serviceDebug includeExceptionDetailInFaults="False"/>
                      </behavior>
                 </serviceBehaviors>
             </behaviors>
        </system.serviceModel>
        <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

服务.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;

namespace MyWCFSolution
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.
    public class Service1 : IService1
    {
        public string CheckSQL(string getJSON)
        {
            string jsonConverted;
            System.Web.Script.Serialization.JavaScriptSerializer serialize = new System.Web.Script.Serialization.JavaScriptSerializer();

            User X = new User();
            User Y = new User();
            User Z = new User();
            opUser operate = new opUser();
            X.AutoID = 1;
            X.Name = "abc";
            X.Password = "12345";
            X.Surname = "ab";
            X.Username = "cde";
            jsonConverted = serialize.Serialize(X);
            Y = (User)serialize.Deserialize(jsonConverted, typeof(User));
            Z = operate.GetUser(Y);
            jsonConverted = serialize.Serialize(Z);
            return "asdf";
        }
    }
}

IService.cs:

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


    namespace MyWCFSolution
    {

        [ServiceContract]
        public interface IService1
        {
            [OperationContract]
            string CheckSQL(User user);

        }
    }

用户.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace MyWCFSolution
{

    public class User
    {
        private Int64 _AutoID;
        private string _Username;
        private string _Password;
        private string _Name;
        private string _Surname;

        public Int64 AutoID { get { return _AutoID; } set { _AutoID = value; } }
        public string Username { get { return _Username; } set { _Username = value; } }
        public string Password { get { return _Password; } set { _Password = value; } }
        public string Name { get { return _Name; } set { _Name = value; } }
        public string Surname { get { return _Surname; } set { _Surname = value; } }
    }

    public class UserList : CollectionBase
    {
        public User this[int index]
        {
            get { return this.List[index] as User; }
        }
        public void Add(User obj)
        {
            this.List.Add(obj);
        }
        public int IndexOf(User obj)
        {
            return this.List.IndexOf(obj);
        }
    }

}

opUser.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace MyWCFSolution
{
    public class opUser
    {
        public User GetUser(User UserD)
        {
            UserList Result = new UserList();
            System.Data.SqlClient.SqlConnection conn = Connection.ConnectToSql();
            User temp = new User();
            try
            {
                conn.Open();

                SqlCommand sqlCommSelect = new SqlCommand("dbo.spSelectUserByPassword", conn);
                sqlCommSelect.CommandType = CommandType.StoredProcedure;
                SqlParameter[] sqlParams = new SqlParameter[] { 
                    new SqlParameter("@Username",UserD.Username ),                   
                    new SqlParameter("@Password",UserD.Password )
                };
                sqlCommSelect.Parameters.AddRange(sqlParams);


                SqlDataReader dr = sqlCommSelect.ExecuteReader();

                while (dr.Read())
                {
                    temp.Name = Convert.ToString(dr["Name"]);
                    temp.Surname = Convert.ToString(dr["Surname"]);

                }
                dr.Close();
                conn.Close();

            }
            catch (Exception exx)
            {
                conn.Close();
                Result = null;

            }
            return temp;
        }

    }
}

这是用于运行 Android 应用程序的 Eclipse 中的 LogCat:

01-11 22:50:43.344: E/oncreate(457): girdi 01-11 22:50:48.955: W/KeyCharacterMap(457): 没有 id 0 的键盘 01-11 22:50:48.955: W/KeyCharacterMap (457): 使用默认键盘映射: /system/usr/keychars/qwerty.kcm.bin 01-11 22:50:50.935: E/json(457): json created 01-11 22:50:50.944: E/response (457): 连接 01-11 22:50:51.164: E/response(457): response getorg.apache.http.message.BasicHttpResponse@405722d0 01-11 22:50:51.174: W/System.err(457) : java.lang.NullPointerException 01-11 22:50:51.184: W/System.err(457): at com.example.logapp.MainActivity$1.onClick(MainActivity.java:95) 01-11 22:50:51.184 : W/System.err(457): 在 android.view.View.performClick(View.java:2485) 01-11 22:50:51.184: W/System.err(457): 在 android.view.View。 onKeyUp(View.java:4257) 01-11 22:50:51.184: W/System.err(457): 在 android.widget.TextView.onKeyUp(TextView.java:4566) 01-11 22:50:51。184: W/System.err(457): 在 android.view.KeyEvent.dispatch(KeyEvent.java:1280) 01-11 22:50:51.184: W/System.err(457): 在 android.view.View .dispatchKeyEvent(View.java:3855) 01-11 22:50:51.184: W/System.err(457): 在 android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:789) 01-11 22:50:51.184 : W/System.err(457): 在 android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:789) 01-11 22:50:51.184: W/System.err(457): 在 android.view.ViewGroup。 dispatchKeyEvent(ViewGroup.java:789) 01-11 22:50:51.194: W/System.err(457): 在 android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:789) 01-11 22:50:51.194: W/System.err(457): 在 com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1687) 01-11 22:50:51.194: W/System.err(457):在 com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1120) 01-11 22:50:51.194: W/System.err(457): 在 android.app.Activity.dispatchKeyEvent(Activity.java:2073) 01-11 22:50:51.194: W/System.err( 457): 在 com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1663) 01-11 22:50:51.194: W/System.err(457): 在 android.view.ViewRoot .deliverKeyEventToViewHierarchy(ViewRoot.java:2560) 01-11 22:50:51.194: W/System.err(457): 在 android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2535) 01-11 22:50:51.204 : W/System.err(457): 在 android.view.ViewRoot.handleMessage(ViewRoot.java:1867) 01-11 22:50:51.204: W/System.err(457): 在 android.os.Handler。 dispatchMessage(Handler.java:99) 01-11 22:50:51.204: W/System.err(457): 在 android.os.Looper.loop(Looper.java:123) 01-11 22:50:51.204: W/System.err(457): 在 android.app.ActivityThread.main(ActivityThread.java:3683) 01-11 22:50:51.204:W/System.err(457): 在 java.lang.reflect.Method.invokeNative(Native Method) 01-11 22:50:51.204: W/System.err(457): 在 java.lang.reflect.Method。调用(Method.java:507)01-11 22:50:51.215:W/System.err(457):在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)01-11 22:50:51.215: W/System.err(457): 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 01-11 22:50:51.215: W/System.err(457 ): 在 dalvik.system.NativeStart.main(Native Method)java:597) 01-11 22:50:51.215: W/System.err(457): 在 dalvik.system.NativeStart.main(Native Method)java:597) 01-11 22:50:51.215: W/System.err(457): 在 dalvik.system.NativeStart.main(Native Method)

HTTP 正在执行。我的意思是,响应来自服务器,但我无法获取 JSON 数据。我尝试使用System.out.print但没有工作来编写 json 数据。Http 连接正常,但无法获取 JSON。为什么会这样?我在这个异常上工作了几天,但没有找到。有人知道吗?

4

1 回答 1

1

下面一行的输出是什么,

        Log.e("response","response get"+response.toString());

...只需检查http请求的responseCode,如果reponseCode是200,那么你很好,

  HttpResponse response = client.execute(httpGet);
      StatusLine statusLine = response.getStatusLine();
      int statusCode = statusLine.getStatusCode();
      if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = reader.readLine()) != null) {
          builder.append(line);
        }
      } else {
        Log.e(ParseJSON.class.toString(), "Failed to download file");
      }

我相信响应代码可能会有所不同,这就是您没有看到 json 响应的原因

于 2013-01-11T21:20:19.520 回答