从Android App发送POST请求到Django视图

时间:2016-03-11 14:43:47

标签: android django

我正在尝试从Android设备读取QRCode并将提取的ID发送到使用Django构建的Web服务器。

我按照教程here将数据正确发送到教程服务器。 然后我只是将发送的数据定制为只是一个整数(id)并将其发送到我的服务器链接,但视图方法根本没有被触发。

我的代码:

Android代码:

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == 0) {
        if (resultCode == RESULT_OK) {
            String data = intent.getStringExtra("SCAN_RESULT");
            new HttpAsyncTask().execute("https://bfish.neuro.mpg.de/baierlab/inventory/");

        }
    }
}

private class HttpAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        String test_data = "111";           

        return POST(urls[0],test_data);
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getBaseContext(), "Data Sent!",       Toast.LENGTH_LONG).show();
    }
}

public static String POST(String url, String data){
    InputStream inputStream = null;
    String result = "";
    try {

        HttpClient httpclient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost(url);

        String json = "";

        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("cross_id", data);

        json = jsonObject.toString();

        StringEntity se = new StringEntity(json);

        httpPost.setEntity(se);

        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        HttpResponse httpResponse = httpclient.execute(httpPost);

        inputStream = httpResponse.getEntity().getContent();

        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }       
    return result;
}

Django查看:

def inventory(request):

    # Just write something on a file to know the method is being fired or not 

    if request.method == 'POST':

        # Try to parse the cross_id from the POST

网址:

url(r'^inventory', views.inventory, name='inventory')

我知道我必须从request.body读取数据,但该方法根本没有被触发。

非常感谢。

0 个答案:

没有答案