android中的JSON请求无法正常工作

时间:2013-03-19 20:27:10

标签: android json web-services rest

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

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

并发送以下json         { “$ ID”: “1”, “雇员”:2 “名字”: “Abayomi”, “姓”: “优素福”, “DepartmentID的”:1, “EmployeeNumber”: “123456”}

这适用于我的浏览器。

现在我正在尝试在我的Android应用中使用该Web服务。 我是初学者,我正在使用Andrew Barber在How to parse JSON in Android创建的JSON解析器类(最后评论)

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 个答案:

答案 0 :(得分:0)

除非我遗漏了某些内容,否则您的问题可能在您的网址中。你正在指定

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

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

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

ipconfig

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

答案 1 :(得分:0)

我创建了一个库,我和我过去一年合作的所有开发人员一起使用过。随意从github克隆它。试一试,看看它是否可以帮助你做休息请求。

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

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

答案 2 :(得分: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;
}

// for Access Web API

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();

        }
    }

答案 3 :(得分:-1)

您需要使用asyncTask进行呼叫服务。

有例子:

private class BackgroundTask extends
                    AsyncTask<String, Object, List<Korisnici>> {

              @Override
                protected List<Korisnici> doInBackground(String... params) {
       //DONT TOUCH GUI OBJECT IN THIS FUNCTION !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
       //CALL DATABASE IN THIS FUNCTION             


            return null;

                }

                @Override
                protected void onPostExecute(List<Korisnici> result) {


                    super.onPostExecute(rezultat);


                    //IN THIS FUNCTION YOU HAVE RESUT FROM DATABASE 
                            //AND YOU CAN CHANGE GUI

                }

            }

当你打电话给任务时:

BackgroundTask task = new BackgroundTask (); 
task.execute();