【问题标题】:How to get a String from Android HTTP post request?如何从 Android HTTP 发布请求中获取字符串?
【发布时间】:2015-06-25 15:04:16
【问题描述】:

我正在向 Web 服务器发送HTTP post 请求以进行登录。它返回字符串值truefalseAsyncTask代码:

    class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{
    HttpResponse httpResponse;
    @Override
    protected String doInBackground(String... params) {

        String paramUsername = params[0];
        String paramPassword = params[1];


        HttpClient httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost("myurl");

        try {


        BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("user", paramUsername);
        BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("password", paramPassword);


        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        nameValuePairList.add(usernameBasicNameValuePair);
        nameValuePairList.add(passwordBasicNameValuePAir);


            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);

            httpPost.setEntity(urlEncodedFormEntity);
            httpResponse = httpClient.execute(httpPost);


            } catch (ClientProtocolException cpe) {
                System.out.println("First Exception caz of HttpResponese :" + cpe);

            } catch (IOException ioe) {
                System.out.println("Second Exception caz of HttpResponse :" + ioe);

            }




        return httpResponse.toString();
    }

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

        String s="true";
        if(result.equalsIgnoreCase(s)){
            Toast.makeText(getApplicationContext(), "Congrats! Login Successful...", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(SignIn.this, Dashboard.class);
            startActivity(intent);


        }else{
            Toast.makeText(getApplicationContext(), "Invalid Username or Password...", Toast.LENGTH_LONG).show();
        }
    }
}

OnCreate代码:

   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_in);
    editTextUserName = (EditText) findViewById(R.id.editTextUserNameToLogin);
    editTextPassword = (EditText) findViewById(R.id.editTextPasswordToLogin);

    Button btnSignIn = (Button) findViewById(R.id.buttonSignIn);
    // btnSignIn.setOnClickListener(this);
    btnSignIn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //if (v.getId() == R.id.buttonSignIn) {
                String givenUsername = editTextUserName.getEditableText().toString();
                String givenPassword = editTextPassword.getEditableText().toString();

           //     System.out.println("Given username :" + givenUsername + " Given password :" + givenPassword);
            new SendPostReqAsyncTask().execute(givenUsername, givenPassword); } }); }

doInBackground 的返回值更改为httpResponse.toString() 也会导致应用崩溃。 我是 Android 新手,即使经过大量搜索似乎也无法解决问题。任何帮助表示赞赏。

编辑:httpResponse 可以通过以下操作转换为字符串:

String response = EntityUtils.toString(httpResponse.getEntity());

【问题讨论】:

  • 您从 doInBackground 返回的内容是您在 onPostExecute 中作为参数接收的内容。在您的情况下,您将返回 null。提示:对 REST API 请求使用改造,这会容易得多。
  • 试试这个editTextUserName.getText()
  • 您正在从 doInBackground 返回 null 到 onPostExecute,这就是它在 result.equalsIgnoreCase(s) 处提供 NPE 的原因
  • onPostExecute 你的result 值是null。你能说出崩溃的行号吗?
  • 但是你在 doInBackground 方法中返回 null 并且你的代码不完整

标签: android android-asynctask http-post


【解决方案1】:

首先将您的 HTTPResponse 转换为字符串。

class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{

    HttpResponse httpResponse;
    String result 

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

        String paramUsername = params[0];
        String paramPassword = params[1];

     try {

        HttpClient httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost("Your URL");
        BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("user", paramUsername);
        BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("password", paramPassword);

        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        nameValuePairList.add(usernameBasicNameValuePair);
        nameValuePairList.add(passwordBasicNameValuePAir);

        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);

        httpPost.setEntity(urlEncodedFormEntity);
        httpResponse = httpClient.execute(httpPost);

        //From here to Convert from HTTPResponse to String
        result= EntityUtils.toString(httpResponse.getEntity());

        } catch (ClientProtocolException cpe) {
            System.out.println("First Exception caz of HttpResponese :" + cpe);

        } catch (IOException ioe) {
            System.out.println("Second Exception caz of HttpResponse :" + ioe);

        }
 return result;
}

【讨论】:

  • 在行中仍然有错误 = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));日志:Caused by: java.lang.NullPointerException at net.delhi.one97.vrindabhatia.wave2.SignIn$SendPostReqAsyncTask.doInBackground(SignIn.java:184) at net.delhi.one97.vrindabhatia.wave2.SignIn$SendPostReqAsyncTask.doInBackground(SignIn.java:142)
  • @VrindaBhatia 是否可以提供您的链接。
  • 响应不是 JSON,它只是返回一个字符串 - 'true' 或 'false'。无法提供链接,因为我正在为公司现有网站开发此应用程序,并且链接是他们的本地主机。您认为链接有问题,我应该再次询问他们吗?
  • @VrindaBhatia 我们可以读取文本文件。我想知道输出到底是怎么来的。
【解决方案2】:

您没有从服务器读取响应并从 doInBackground() 返回 null 到 onPostExecute()。您需要像这样从 httpresponse 读取输入流:

String result = "";
HttpResponse httpResponse = httpclient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
     BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(inputStream));
     String line = "";
     while ((line = bufferedReader.readLine()) != null)
          result += line;
     inputStream.close();
     bufferedReader.close();
}

现在您可以从doInbackground() 返回result

【讨论】:

    【解决方案3】:

    用这个来请求

    public String request(String url, List<NameValuePair> nameValuePairs) {
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            // httpPost.setHeader("encytype", "multipart/form-data");
    
            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8);
            httpPost.setEntity(entity);
    
            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");
            }
            reader.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Buffer Error" + "Error converting result " + e.toString());
        }
    
        return json;
    }
    

    【讨论】:

      【解决方案4】:

      首先使用 Log.d 检查您是否收到响应,如下所示:

      httpPost.setEntity(urlEncodedFormEntity);
      httpResponse = httpClient.execute(httpPost);
      String response = EntityUtils.toString(httpResponse.getEntity());
      Log.d("Response","Response from http:"+response);
      

      在 Logcat 中检查它所显示的内容以代替响应。如果它什么都不显示,那么有两种可能性。一是服务器端响应未正确发送。其次可能是网络问题或 url 不正确。请检查并告诉我。如果可能,还显示 logcat 输出。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多