【问题标题】:http post method passing null values to the serverhttp post方法将空值传递给服务器
【发布时间】:2012-10-30 06:50:27
【问题描述】:
         try 
         {

            url= new URL(ConstantsClass.VENDOR_FOLLOW + "?UID=" +android_id+"&URL='"+resultfinal+"'&device=android");


                connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");

                request = new OutputStreamWriter(connection.getOutputStream());
                request.flush();
                request.close();
                request.write("Hello!!!");

                String line = "";
                InputStreamReader isr = new InputStreamReader(connection.getInputStream());
                BufferedReader reader = new BufferedReader(isr);

                StringBuffer sb = new StringBuffer();

                while((line=reader.readLine())!=null) {
                    sb.append(line + "&");
                }

                response = sb.toString();
                //response.getEntity().getContent();

                Log.i("Test", "updated response: " + response);



            }
         catch (IOException e) {
              e.printStackTrace();
          }

            Log.i("Test", "**************url list********************" + url);
         tag_text.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent in=new Intent(context,LinkWebView.class);
                    in.putExtra("vendorUrl", resultfinal);
                    context.startActivity(in);      
                    //postData();
                }
            });
             }

    tag_text.setTextSize(16);
    return view;

}   

您好,我是 android 新手,我正在尝试将值从 url 传递到服务器,但我在服务器端传递了空值。更新响应为空。我的服务器端值没有给我任何值。我需要从上面给出的 url 传递 url、android_id 和设备。我也尝试了 httpclient,但它也给了我空值。

【问题讨论】:

  • 在传递给 URL 之前检查您是否正确获取了所有值。顺便说一句,“resultfinal”包含什么??
  • resultfinal 有一个我正在传递的网址。我已经在 toast 上打印了这个 url 值,它正确地给了我所有的值
  • android_id 是数字还是字符串?
  • android_id是获取系统android_id的字符串
  • 你的错误将在 " +android_id+" 你将不得不在 ("") 之外添加单个 ('')

标签: android http


【解决方案1】:

你应该试试下面的代码,它对我来说运行得很好。

   // ADD YOUR REQUEST DATA HERE  (you can pass number of variable).
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("Your_var_1", value));
    nameValuePairs.add(new BasicNameValuePair("Your_var_2", value));

现在建立您的网络连接,如

(1) 向服务器发送简单字符串

    try
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("your url only ex:www.google.com/abc");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpParams httpParameters = new BasicHttpParams();
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch (Exception e) 
    {   
        Log.e("Loading Runnable Error in http connection  :", e.toString());
    }

(2) 发送 JSON Encode 字符串到服务器

HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();

try {
HttpPost post = new HttpPost(URL);
json.put("user_name", "chintan");
json.put("password", "khetiya");
StringEntity se = new StringEntity( json.toString());  
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);

 /*Checking response */
if(response!=null){
is = response.getEntity().getContent(); //Get the data in the entity
 }

} catch(Exception e) {
e.printStackTrace();
createDialog("Error", "Cannot Estabilish Connection");
}

两种情况下的响应都相同

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");
        }
        is.close();
        result = sb.toString();
    }
    catch (Exception e) 
    {   
        Log.e("Loading Runnable Error converting result :", e.toString());
    }

现在最终结果包含整个输出字符串,这取决于您将如何读取数据。使用 json 或其他。我正在使用 json,所以放上它的示例代码可能对你有帮助。

JSONObject json_data = new JSONObject(result);// its a string var which contain output. 
        my_output_one = json_data.getString("var_1"); // its your response var form web.
        my_output_two = json_data.getString("var_2");

现在你有两个变量,它们具有任何类型的值并使用任何类型。

现在这将对您有所帮助。如果您有任何疑问,请告诉我。

【讨论】:

  • 嗨 chintan 我也尝试过这样做,但它仍然只给出空值
  • 当我把 Toast 打印到 url 时,我给了我正确的值,所有的值都是正确的。
  • php 我有它的日志文件,但它在服务器端给了我空值
  • 是的,但我需要获取传递的参数并将这些参数发送到服务器,目前我也可以访问 jsp 页面。
  • 所以在您的 postData() 中将 var 发送到网络并根据请求检索响应。所以告诉我你的所有 4 个变量都有一个值或任何 null 吗?
【解决方案2】:

请在写入后调用flush并关闭finally块中的流。查看以下代码:

   try 
         {

            url= new URL(ConstantsClass.VENDOR_FOLLOW + "?UID=" +android_id+"&URL='"+resultfinal+"'&device=android");


                connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");

                request = new OutputStreamWriter(connection.getOutputStream());
                request.write("Hello!!!");

                request.flush();


                String line = "";
                InputStreamReader isr = new InputStreamReader(connection.getInputStream());
                BufferedReader reader = new BufferedReader(isr);

                StringBuffer sb = new StringBuffer();

                while((line=reader.readLine())!=null) {
                    sb.append(line + "&");
                }

                response = sb.toString();
                //response.getEntity().getContent();

                Log.i("Test", "updated response: " + response);



            }
         catch (IOException e) {
              e.printStackTrace();
          }

            Log.i("Test", "**************url list********************" + url);
         tag_text.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent in=new Intent(context,LinkWebView.class);
                    in.putExtra("vendorUrl", resultfinal);
                    context.startActivity(in);      
                    //postData();
                }
            });
             }

    tag_text.setTextSize(16);
    return view;

}finally{
              try{
                request.close();
              }catch(Exception e){}
 } 

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-08-22
  • 1970-01-01
  • 2017-03-07
  • 2012-07-03
  • 2016-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多