HTTP Post Request在Android中给出NULL

时间:2015-10-22 12:06:52

标签: android apache android-activity http-post

我正在尝试发送有关API的一些数据。但是我的APP没有给出任何回复。既没有给出任何错误也没有停止。它就像刚刚发生的一样。我有点新的知识分子这么善良的指导。此外,我知道HTTPClient和其他导入已被弃用。

public void makePostRequest()
{
    class makePostRequestAsyncTask extends AsyncTask<Void, Void, String> {


        @Override
        protected String doInBackground(Void... params) {

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://103.226.216.209/finger_varification/api/finger_verification");
            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(7);
            nameValuePair.add(new BasicNameValuePair("sec_key", "2af8b9d956c39d2d52c46c2a02a978d1"));
            nameValuePair.add(new BasicNameValuePair("cnic", "3520214037921"));
            nameValuePair.add(new BasicNameValuePair("imei_no", "864121017028886"));
            nameValuePair.add(new BasicNameValuePair("device_name", "FingerMap5"));
            nameValuePair.add(new BasicNameValuePair("finger_index",index ));
            nameValuePair.add(new BasicNameValuePair("finger_template", "sdsd"));//model1.toString()));
            nameValuePair.add(new BasicNameValuePair("template_type", "RAW_IMAGE"));

            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
            } catch (UnsupportedEncodingException e) {
                // log exception
                e.printStackTrace();
            }


            //making POST request.
            try {
                HttpResponse response = httpClient.execute(httpPost);
                // write response to log

                Log.d("Http Post Response:", response.toString());
            } catch (ClientProtocolException e) {
                // Log exception
                e.printStackTrace();
            } catch (IOException e) {
                // Log exception
                e.printStackTrace();
            }

            return null;
        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            if(result.equals("working")){
                Toast.makeText(getApplicationContext(), "HTTP POST is working...", Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(getApplicationContext(), "Invalid POST req...", Toast.LENGTH_LONG).show();
            }
        }


    }

}

1 个答案:

答案 0 :(得分:0)

这就是你如何得到回应的主体

HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String response_body = reader.readLine();
Log.d("Http Post Response:", response_body);

顺便说一句,在API 23上弃用 HttpPost HttpResponse ,请改用 HttpURLConnection