Volley在Emulator上运行但在设备上失败

时间:2017-04-21 19:37:44

标签: java android android-volley

我有一台LG G3,当我运行我的应用程序时,Volley无法正常工作。我正在做的就是向我的本地服务器发送一个发布请求,它在模拟器上完美运行但在设备上失败。我得到的错误是超时错误。这是代码:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Button button = (Button) findViewById(R.id.button);
        final TextView textview = (TextView) findViewById((R.id.test));
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendRequest("example", "0", "0", "0", "0", "0", "0");

            }
        });
    }


    public void sendRequest(final String location, final String mood, final String gender, final String age,
                            final String day, final String month, final String year) {

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String url = "http://10.0.2.2:8000/polls/add/";

        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(MainActivity.this, "works", Toast.LENGTH_SHORT).show();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "Error is: " + error.toString(),
                        Toast.LENGTH_LONG).show();
                Log.e("VOLLEY", error.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> parameters = new HashMap<>();
                parameters.put("age", age);
                parameters.put("location", location);
                parameters.put("mood", mood);
                parameters.put("gender", gender);
                parameters.put("day", day);
                parameters.put("month", month);
                parameters.put("year", year);
                return parameters;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("Content-Type", "application/x-www-form-urlencoded");
                return params;
            }
        };
        requestQueue.add(stringRequest);
    }
}  

任何帮助都会非常感激。谢谢!

1 个答案:

答案 0 :(得分:0)

如果您想使用本地服务器,则应使用网内IP ...例如 192.168.1.105 而不是本地IP地址(10.0.2.2 - 127.0.0.1 - 等) )

所以...只需使用ipconfig/all找到PC的IP地址,然后:

String url = "http://192.168.1.105:8000/polls/add/";