【问题标题】:connecting to server http Client连接到服务器 http 客户端
【发布时间】:2014-03-13 17:48:13
【问题描述】:
try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://nayyar.5gbfree.com/welcome.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost); 
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

                Log.e("log_tag", "connection success ");
Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
           }

我第一次尝试连接到服务器。我从互联网复制代码试图执行。但总是在 nameValuePairs 上显示错误。我不知道这是什么。以及错误的原因。任何人都向我解释代码和错误,或者解释我通过代码以他/她自己的方式连接到服务器。将不胜感激。

【问题讨论】:

  • 不,我们不会给你代码。在发布您编写的代码的问题时,始终说明您的目标。如果有错误,总是发布堆栈跟踪或编译器错误。或者解释它在您的期望方面的表现。
  • 也就是说,你应该声明那些nameValuePairs!
  • 错误:nameValuePairs 无法解析为变量
  • 您是否尝试过查找该错误?老实说,你根本没有表现出任何努力。

标签: java android json apache httpclient


【解决方案1】:

你必须创建一个 NameValuePair 列表...像这样

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://nayyar.5gbfree.com/welcome.php");
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
                    postParameters);
httppost.setEntity(formEntity);
HttpResponse response = httpclient.execute(httppost); 

然后这样获取数据

BufferedReader br = new BufferedReader(new InputStreamReader(
                    httppost.getEntity().getContent()));

br.readLine(); // Save it in a String variable or whatever you want 

【讨论】:

    【解决方案2】:

    您的 POST 必须接收哪些数据?例如,如果 url 需要“id”和“user”:

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://nayyar.5gbfree.com/welcome.php");
    
                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("id", "12345"));
                nameValuePairs.add(new BasicNameValuePair("user", "Jorgesys!"));
    
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        ...
        ...
        ...
    

    【讨论】:

      猜你喜欢
      • 2020-06-26
      • 2022-01-17
      • 2013-12-26
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2016-07-06
      • 1970-01-01
      相关资源
      最近更新 更多