6
         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;

}   

Hi i am new to android and I am trying to pass values from the url to the server but i am getting null values passed on the server side. Update response is giving null. My server side values dont give any values to me. I need to pass the url, android_id and device from the url that is given above. I tried the httpclient also but it gives me null values in that as well.

android_developer
  • 663
  • 2
  • 13
  • 18

2 Answers2

12

you should try below code its running very well for me.

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

Now establish your web connection like

(1) Sending simple string to server

    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) Send JSON Encode string to server

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");
}

Response will same in both case

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());
    }

Now at the end result contain whole output string now its depend on you how you will read your data. using json or else. i am doing using json so put example code of it may be helpful to you.

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

Now its over you have two variable which having any kind of value and use any were.

Now this will helpful to you. if you have any query let me know.

Chintan Khetiya
  • 15,962
  • 9
  • 47
  • 85
  • Hi chintan i have tried doing this as well it still gives null values only – android_developer Oct 30 '12 at 07:15
  • When i put a Toast to print url i gives me correct values all the values are correct. – android_developer Oct 30 '12 at 07:27
  • php i have its log file with me but it gives me null values on the server side – android_developer Oct 30 '12 at 07:36
  • yes but i need to fetch the pararmeter passing and send those parameters to the server currently i can go to the jsp page as well. – android_developer Oct 30 '12 at 07:45
  • so in your postData() that send the var to web and retrieve the response according to request. so tell me that your all 4 var having a value or any null ? – Chintan Khetiya Oct 30 '12 at 10:14
  • that i know before that you directly pass argu in url . at that time your argu contain any value ? that i want to know. did you get my point. i want to check that if there are no any value at sending time then it will not response. and if that having a value it mean that sending request but at service side you have to concern with your service developer and handle . hope you got my concept. – Chintan Khetiya Oct 30 '12 at 10:53
  • its my pleasure.remind me if any other query i will try to help you. – Chintan Khetiya Oct 30 '12 at 11:19
  • you should use EntityUtils.toString, rather than reinventing reading a string from a stream. – njzk2 Dec 11 '12 at 08:38
  • @njzk2 i think you are talking about buffer ? can you suggest me how is it ? – Chintan Khetiya Dec 11 '12 at 08:40
  • you can replace ~10 lines of reading from an inputstream (creating the bufferedthing, readlines ...) by a single : `result = EntityUtils.toString(entity)` – njzk2 Dec 11 '12 at 08:42
  • my last syntax is entity.getContent(); and that i have to add in your syntax ?is it ? – Chintan Khetiya Dec 11 '12 at 08:47
1

Please call the flush after write and close the stream in finally block. Check out the following code:

   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){}
 } 
Praful Bhatnagar
  • 7,425
  • 2
  • 36
  • 44
  • No its still giving me null values only – android_developer Oct 30 '12 at 07:12
  • Please try some rest tool to check that the request that you are sending is right and the server is sending some response. You can use following rest plug in to test that: https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo – Praful Bhatnagar Oct 30 '12 at 07:17