1

我在 asp.net 中创建了一个 Web 服务,它接收以下 url:

http://localhost:31804/api/defaultapi/login?empNum=123456&surname=Yusuf 

并发送以下 json {"$id":"1","EmployeeID":2,"Firstname":"Abayomi","Surname":"Yusuf","DepartmentID":1,"EmployeeNumber":"123456" }

这适用于我的浏览器。

现在我正在尝试在我的 android 应用程序中使用该 Web 服务。我是一个初学者,我在这里使用 Andrew Barber 创建的 JSON 解析器类How to parse JSON in Android (last comment)

public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

// Making HTTP request
try {
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            is, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    is.close();
    json = sb.toString();
} catch (Exception e) {
    Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
    jObj = new JSONObject(json);
} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}
}

这就是我在代码中使用它的方式。按钮具有 loadHome 方法作为其 onClick 事件

public class Main extends Activity {

private SharedPreferences employeeDetails;

private static final String EMP_ID = "EmployeeID";
private static final String EMP_NAME = "Firstname";

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

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

public void loadHome(View view)
{
    EditText empNumEditText = (EditText)findViewById(R.id.employeeNumEditText);
    EditText surnameEditText = (EditText)findViewById(R.id.surnameEditText);
    TextView empNumError = (TextView)findViewById(R.id.empNumWarningTextView);
    TextView surnameError = (TextView)findViewById(R.id.surnameWarningTextView);
    TextView displayError = (TextView)findViewById(R.id.errorTextView);

    String employeeNumber = empNumEditText.getText().toString();
    String surname = surnameEditText.getText().toString();

    //ensure that the form was completed
    if((employeeNumber.length()>0) && (surname.length()>0))
    {
        try{
            String encodedEmployeeNumber = URLEncoder.encode(employeeNumber, "UTF-8");
            String encodedSurname = URLEncoder.encode(surname, "UTF-8");

            String loginURL = "localhost:31804/api/defaultapi/login?empNum=" + encodedEmployeeNumber + "&surname=" + encodedSurname;


            // Creating JSON Parser instance
            JSONParser jParser = new JSONParser();

            // getting JSON string from URL
            JSONObject json = jParser.getJSONFromUrl(loginURL);
            String empId = json.getString(EMP_ID);
            String empSur = json.getString(EMP_NAME);

            displayError.setText(empSur);
            }
        catch(Exception e){
            displayError.setText("Whoops - something went wrong!");
            e.printStackTrace();
        }

    } 
    else //display error messages
    {
        if (employeeNumber.length()>0){
            empNumError.setText(" ");
        }else{
            empNumError.setText("Enter Your Employee Number");
        }

        if (surname.length()>0){
            surnameError.setText(" ");
        }else{
            surnameError.setText("Enter Your Surname");
        }
    }

}

我在 displayError textView 中不断收到错误消息(“哎呀 - 出了点问题!”)。我究竟做错了什么。

这是堆栈跟踪的链接 http://3.bp.blogspot.com/-jJnZ71KC5ZM/UUjVQhbzKCI/AAAAAAAAAMk/v9j_bhIkOEg/s1600/1.jpg

4

3 回答 3

0

我创建了一个库,我在过去一年中与所有与我一起工作的开发人员一起使用过。随意从 github 克隆它。尝试一下,看看它是否可以帮助您完成休息请求。

https://github.com/darko1002001/android-rest-client

它可以帮助您处理请求的异步执行,并在带有线程池的单独服务中执行它们以管理并发连接。

于 2013-05-17T09:51:43.310 回答
0

除非我遗漏了什么,否则您的问题可能出在您的网址中。你指定

String loginURL = "localhost:31804/api/defaultapi/login?empNum=" + encodedEmployeeNumber + "&surname=" + encodedSurname;

主机名“localhost”应始终解析为 127.0.0.1。任何 127.xxx 地址都应指向您的本地堆栈...因此,如果您在手机上运行,​​这将是您的手机。根据您的配置,在 AVD 中运行时它可能是您的 AVD。尝试将其更改为可路由端口,看看是否有所不同。

如果您在 Windows 上,请转到命令提示符并使用:

ipconfig

查找您的 LAN 适配器并使用 IPv4 地址而不是“localhost”。

于 2013-03-19T23:17:21.923 回答
0
String response = performRequestAsString(MY_URL, "GET");
Log.v("REsponse from web server",response);

// 把它放在下面

public static String performRequestAsString(String url, String method) 
{
    String value = null;

    try {

        if (method == "POST") {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            Log.e("Request_Url", "" + url);
            HttpPost httpPost = new HttpPost(url);              
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream is = httpEntity.getContent();
            value = convertStreamToString(is);

        } else if (method == "GET") {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            Log.e("Request_Url", "" + url);
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream is = httpEntity.getContent();
            value = convertStreamToString(is);
        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        // e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return value;
}

// 用于访问 WebAPI

new GetData().execute();


private class GetData extends AsyncTask<String, String, String> {
        private ProgressDialog progressDialog;
        private String response = "";
        private JSONArray jRootArray;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(mContext);
            progressDialog.setMessage("Loading ...");
            progressDialog.setIndeterminate(false);
            progressDialog.setCancelable(false);
            progressDialog.show();

        }

        @Override
        protected String doInBackground(String... args) {

            response = WebAPIRequest.performRequestAsString(MY_URL, "GET");


            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    if (response == null) {

                        Toast.makeText(mContext, "Please Try Again",
                                Toast.LENGTH_SHORT).show();
                    } else {

                    }

                }
            });
            return null;
        }

        @Override
        protected void onPostExecute(String args) {
            progressDialog.dismiss();

        }
    }
于 2013-09-09T12:48:31.037 回答