【问题标题】:Android HttpPost: how to get the resultAndroid HttpPost:如何获得结果
【发布时间】:2010-02-24 04:12:31
【问题描述】:

我一直在尝试发送 HttpPost 请求并检索响应,但即使我能够建立连接,我仍然不知道如何获取请求响应返回的字符串消息

 HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost("http://www.myurl.com/app/page.php");
 // Add your data   
 List < NameValuePair > nameValuePairs = new ArrayList < NameValuePair > (5);
 nameValuePairs.add(new BasicNameValuePair("type", "20"));
 nameValuePairs.add(new BasicNameValuePair("mob", "919895865899"));
 nameValuePairs.add(new BasicNameValuePair("pack", "0"));
 nameValuePairs.add(new BasicNameValuePair("exchk", "1"));

 try {
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
     Log.d("myapp", "works till here. 2");
     try {
         HttpResponse response = httpclient.execute(httppost);
         Log.d("myapp", "response " + response.getEntity());
     } catch (ClientProtocolException e) {
         e.printStackTrace();
     } catch (IOException e) {
         e.printStackTrace();
     }
 } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
 } 

对不起,我听起来很幼稚,因为我是 Java 新手。请帮帮我。

【问题讨论】:

  • 嗨,我看到了这篇文章,我想知道你能否告诉我为什么你的 ArrayList 是 (5) 而不是 (4)?
  • 我在发布之前删除了一个参数,只是忘记更改数组列表。
  • “HttpClient”、“HttpPost”、“HttpResponse”、“HttpEntity”、“EntityUtils”、“NameValuePair”、“BasicNameValuePair”已弃用。请提出其他解决方案。

标签: java android http


【解决方案1】:

尝试在您的回复中使用EntityUtil

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

【讨论】:

  • 您好 Soulreaper,感谢您的回复。但是为什么要使用 EntityUtils 呢?
  • 这只是将包含的原始字节答案提取为字符串形式的便捷方法。
  • 从 API 级别 22 开始,EntityUtils 已弃用。就像整个 org.apache.http 包一样。
  • @Moritz:我们发送到服务器的参数的名称是什么。我的意思是我填写的文本框的“id”还是它的“名称”?谢谢。
【解决方案2】:
    URL url;
    url = new URL("http://www.url.com/app.php");
    URLConnection connection;
    connection = url.openConnection();
    HttpURLConnection httppost = (HttpURLConnection) connection;
    httppost.setDoInput(true);
    httppost.setDoOutput(true);
    httppost.setRequestMethod("POST");
    httppost.setRequestProperty("User-Agent", "Tranz-Version-t1.914");
    httppost.setRequestProperty("Accept_Language", "en-US");
    httppost.setRequestProperty("Content-Type",
            "application/x-www-form-urlencoded");
    DataOutputStream dos = new DataOutputStream(httppost.getOutputStream());
    dos.write(b); // bytes[] b of post data

    String reply;
    InputStream in = httppost.getInputStream();
    StringBuffer sb = new StringBuffer();
    try {
        int chr;
        while ((chr = in.read()) != -1) {
            sb.append((char) chr);
        }
        reply = sb.toString();
    } finally {
        in.close();
    }

此代码 sn-p 有效。 我在搜索之后得到了它,但是来自 J2ME 代码。

【讨论】:

  • 您在哪里添加了要与 url 一起发送的值?
  • httppost.setRequestProperty("parameter_variable_name",value) - 我想这会起作用。抱歉,有一段时间我尝试过类似的东西。记不太清了。
  • 只是告诉你,这个片段已经过时了很多年,还有另一种运行 httppost 请求的方法。
【解决方案3】:

您可以使用 ResponseHandler 调用执行方法。这是一个例子:

ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpClient.execute(httppost, responseHandler);

【讨论】:

  • 嗨 Sarp,感谢您的回复。但是,使用这个有什么好处呢?
【解决方案4】:

你可以这样做:

 public class MyHttpPostProjectActivity extends Activity implements OnClickListener {

        private EditText usernameEditText;
        private EditText passwordEditText;
        private Button sendPostReqButton;
        private Button clearButton;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.login);

            usernameEditText = (EditText) findViewById(R.id.login_username_editText);
            passwordEditText = (EditText) findViewById(R.id.login_password_editText);

            sendPostReqButton = (Button) findViewById(R.id.login_sendPostReq_button);
            sendPostReqButton.setOnClickListener(this);

            clearButton = (Button) findViewById(R.id.login_clear_button);
            clearButton.setOnClickListener(this);        
        }

        @Override
        public void onClick(View v) {

            if(v.getId() == R.id.login_clear_button){
                usernameEditText.setText("");
                passwordEditText.setText("");
                passwordEditText.setCursorVisible(false);
                passwordEditText.setFocusable(false);
                usernameEditText.setCursorVisible(true);
                passwordEditText.setFocusable(true);
            }else if(v.getId() == R.id.login_sendPostReq_button){
                String givenUsername = usernameEditText.getEditableText().toString();
                String givenPassword = passwordEditText.getEditableText().toString();

                System.out.println("Given username :" + givenUsername + " Given password :" + givenPassword);

                sendPostRequest(givenUsername, givenPassword);
            }   
        }

        private void sendPostRequest(String givenUsername, String givenPassword) {

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

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

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

                    System.out.println("*** doInBackground ** paramUsername " + paramUsername + " paramPassword :" + paramPassword);

                    HttpClient httpClient = new DefaultHttpClient();

                    // In a POST request, we don't pass the values in the URL.
                    //Therefore we use only the web page URL as the parameter of the HttpPost argument
                    HttpPost httpPost = new HttpPost("http://www.nirmana.lk/hec/android/postLogin.php");

                    // Because we are not passing values over the URL, we should have a mechanism to pass the values that can be
                    //uniquely separate by the other end.
                    //To achieve that we use BasicNameValuePair             
                    //Things we need to pass with the POST request
                    BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("paramUsername", paramUsername);
                    BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("paramPassword", paramPassword);

                    // We add the content that we want to pass with the POST request to as name-value pairs
                    //Now we put those sending details to an ArrayList with type safe of NameValuePair
                    List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
                    nameValuePairList.add(usernameBasicNameValuePair);
                    nameValuePairList.add(passwordBasicNameValuePAir);

                    try {
                        // UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs. 
                        //This is typically useful while sending an HTTP POST request. 
                        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);

                        // setEntity() hands the entity (here it is urlEncodedFormEntity) to the request.
                        httpPost.setEntity(urlEncodedFormEntity);

                        try {
                            // HttpResponse is an interface just like HttpPost.
                            //Therefore we can't initialize them
                            HttpResponse httpResponse = httpClient.execute(httpPost);

                            // According to the JAVA API, InputStream constructor do nothing. 
                            //So we can't initialize InputStream although it is not an interface
                            InputStream inputStream = httpResponse.getEntity().getContent();

                            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

                            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                            StringBuilder stringBuilder = new StringBuilder();

                            String bufferedStrChunk = null;

                            while((bufferedStrChunk = bufferedReader.readLine()) != null){
                                stringBuilder.append(bufferedStrChunk);
                            }

                            return stringBuilder.toString();

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

                    } catch (UnsupportedEncodingException uee) {
                        System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
                        uee.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();
                    }
                }           
            }

            SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
            sendPostReqAsyncTask.execute(givenUsername, givenPassword);     
        }
    }

【讨论】:

  • 嗨,Siddhpura,你是同时写作和阅读吗?我应该怎么做才能发送信息?我试着像你一样做,但它对我不起作用。使用 POST 方法发送数据的确切部分是什么?谢谢!
  • @Siddhpura:我必须为参数名称输入什么值?我的意思是它的参数的“id”是“name”吗?请帮我。谢谢。
【解决方案5】:

试试这个,它似乎是最紧凑的。尽管在现实世界中,您需要使用异步请求,以便在检索请求的页面时设备不会挂起。

http://www.softwarepassion.com/android-series-get-post-and-multipart-post-requests/

【讨论】:

    【解决方案6】:

    您应该尝试使用 HttpGet 而不是 HttpPost。我有一个类似的问题,并解决了它。

    【讨论】:

      猜你喜欢
      • 2013-07-05
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 2019-11-06
      • 2014-04-25
      • 1970-01-01
      相关资源
      最近更新 更多