【问题标题】:JSON request in android not workingandroid中的JSON请求不起作用
【发布时间】:2013-03-19 20:27:10
【问题描述】:

我在 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(最后评论)

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

【问题讨论】:

  • 发布异常的堆栈跟踪。
  • @GabeSechan 我已经包含了堆栈跟踪
  • @ylinkz :您的网址以 localhost 开头,这让我觉得您是在与 asp.net 服务相同的机器上的模拟器上运行它 - 对吗?如果是这样,那就不要使用localhost,你需要使用数字IP地址10.0.2.2。请参阅模拟器网络文档developer.android.com/tools/devices/…
  • @Squonk,我发现我什至无法在模拟器的浏览器上浏览我的本地 Web 应用程序。我已经尝试了 10.0.2.2,我什至使用了 Dave 在下面的评论中建议的 IPv4 地址,仍然没有运气。我想在我什至可以调用本地网络服务之前,它必须工作,对吧?
  • @ylinkz :地址 10.0.2.2 对于访问开发机器的环回接口是正确的。不要像 Dave 建议的那样使用 IPv4 地址。使用 10.0.2.2 重试,然后发布堆栈跟踪。

标签: android json web-services rest


【解决方案1】:

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

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”。

【讨论】:

  • 我无法添加 cmets,但是,为了回答您的其他问题之一。是的,您首先需要让它在浏览器中运行——至少要对其进行测试。我的建议是制作一个非常简单的页面来返回一些文本。确保你可以浏览到那个(这将把除了浏览器之外的所有东西都排除在循环之外)。如果您可以做到这一点,请针对该 URL 运行您的应用程序并查看该应用程序是否获得结果。如果是这样,您就知道您正在与服务器通信正常。然后让您的 API 正常工作。
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:
    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();
    
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-15
      • 1970-01-01
      • 2014-03-31
      相关资源
      最近更新 更多