连接到服务器http客户端

时间:2014-03-13 17:48:13

标签: java android json apache httpclient

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上显示错误。我不知道这是什么。以及错误的原因。任何人解释我的代码和错误或解释我通过代码以他/她自己的方式连接到服务器。要非常感激。

2 个答案:

答案 0 :(得分:0)

你必须制作一个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 

答案 1 :(得分:0)

您的POST必须接收哪些数据?例如,如果网址需要&#34; id&#34;和&#34;用户&#34;:

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));
    ...
    ...
    ...