2

我已经开发了一个将数据发送到服务器的应用程序,但是当我尝试运行它时,我在执行 http 请求时遇到错误......

这是代码...

    public void send()
    {
        // get the message from the message text box
        String msg = msgTextField.getText().toString();  
        System.out.println("I am here!!!");
        // make sure the fields are not empty
        if (msg.length()>0)
        {

            Toast.makeText(this, "started", Toast.LENGTH_LONG).show();
            DefaultHttpClient httpclient=new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.fblocation.asia/update/index.php");
           List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
           nameValuePairs.add(new BasicNameValuePair("lat", Double.toString(clat)));
           nameValuePairs.add(new BasicNameValuePair("long", Double.toString(clong)));
           nameValuePairs.add(new BasicNameValuePair("username", msg));
         try {
           httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
           httpclient.execute(httppost);
           Toast.makeText(this, "sent", Toast.LENGTH_LONG).show();
         } catch (Exception e) {
             Toast t=Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_LONG);
             t.show();
         }

        }
        else
        {
            // display message if text fields are empty
            Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
        }

    }

请给我一些建议。

谢谢!

4

2 回答 2

3

请尝试此代码

HttpClient httpclient = new DefaultHttpClient();
        String responseStr="";
        String URL=Constants.API_URL+"details/";
        HttpPost httppost = new HttpPost(URL);

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("id", pick_up_id));
            nameValuePairs.add(new BasicNameValuePair("username", username));
            nameValuePairs.add(new BasicNameValuePair("password", password));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            int responseCode = response.getStatusLine().getStatusCode();
            switch(responseCode) {
            case 200:
                HttpEntity entity = response.getEntity();
                if(entity != null) {
                    String responseBody = EntityUtils.toString(entity);
                    responseStr=responseBody;
                }
                break;
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
        System.out.println("this is response "+responseStr);
于 2013-04-29T13:46:03.943 回答
0

你必须异步进行http调用。这意味着您的代码需要进行一些重大更改,并且需要几天的练习。按照评论中的链接获取 AsyncTask 的第一印象。

这个指南也很扎实!!

于 2013-04-29T13:45:42.880 回答