0

i have a url "http://184.82.158.234/~store/rest/system/connect.json" and posting this url with mozilla addon called poster returns data in form of json what i want is to post this url from android to get that json data into androids view .

any help is highly appreciated thanks

Shoaib Ahmed
  • 747
  • 12
  • 28

3 Answers3

1
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://184.82.158.234/~store/rest/system/connect.json");

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

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

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}
} 

response variable will contain your json data.

Abhay Kumar
  • 1,582
  • 1
  • 19
  • 45
  • 1
    brother i have already tried ur solution not working thanks for reply – Shoaib Ahmed May 14 '12 at 07:18
  • 1
    and can u plz tell me y i have to do this nameValuePairs.add(new BasicNameValuePair("id", "12345")); since my url dont take any parameter it just returns data without any parameters – Shoaib Ahmed May 14 '12 at 07:20
  • 1
    are you not able to parse the json ? can you expain your problem a bit more – Abhay Kumar May 14 '12 at 07:20
  • 1
    You need not add any name value pair if you link doesnt take any parameter – Abhay Kumar May 14 '12 at 07:22
  • 1
    i getting exception saying json not parsed and what i simply want is to fetch the data returned by my url in android is unable to catch the data from it :( – Shoaib Ahmed May 14 '12 at 07:35
  • http://stackoverflow.com/questions/2845599/how-do-i-parse-json-from-a-java-httpresponse this may help you – Abhay Kumar May 14 '12 at 07:40
  • i added this which removed the exception i was getting inline 'removes android.os.NetworkOnMainThreadException exception StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); ' – Shoaib Ahmed May 16 '12 at 07:35
1

check below code: try this it may help you.

    ArrayList nameValuePairs1 = new ArrayList();

        nameValuePairs1.add(new BasicNameValuePair("user_id", "")); 
        nameValuePairs1.add(new BasicNameValuePair("product_id", "")); 
        nameValuePairs1.add(new BasicNameValuePair("product_review",""+text));

        HttpClient httpclient = new DefaultHttpClient();

        HttpPost httppost = new HttpPost(URL);

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));

        HttpResponse responce = httpclient.execute(httppost);

        HttpEntity entity = responce.getEntity();

        is = entity.getContent();

        BufferedReader bufr = new BufferedReader(new InputStreamReader(is1,"iso-8859-1"), 8);

        StringBuilder sb = new StringBuilder();

        sb.append(bufr.readLine() + "\n");

        String line = "0";

        while ((line = bufr.readLine()) != null)

        {

        sb.append(line + "\n");

        }

        is1.close();

        result = sb.toString();

result is a json String. parse that json and display in any control. i displaied that in text view see below.

final MyProgressDialog progDailog = new MyProgressDialog(Cheking_Review.this);
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (Name.length() > 0 && Name != null) {
                    txtvenue.setText(Name);
                } else {
                    txtvenue.setText(venue_name);
                }
            }
        };

        new Thread() {

            public void run() {
                try {

// put your result here
                    JSONObject jObject = new JSONObject(result);
                    JSONObject menuObject = jObject.getJSONObject("response");
                    JSONObject venueObject = menuObject.getJSONObject("venue");
                    Name = venueObject.getString("name");

                    String id = venueObject.getString("id");

                    Log.d("--------name---------", Name);
                    Log.d("--------id---------", id);

                } catch (Exception e) {
                }
                handler.sendEmptyMessage(0);
                progDailog.dismiss();
            }
        }.start();
Dhaval Parmar
  • 18,812
  • 8
  • 82
  • 177
  • 1
    ok let me try can u plz tell me what is this ? `code` nameValuePairs1.add(new BasicNameValuePair("user_id", "")); nameValuePairs1.add(new BasicNameValuePair("product_id", "")); nameValuePairs1.add(new BasicNameValuePair("product_review",""+text));`code` since i get the responce without any parameters – Shoaib Ahmed May 14 '12 at 07:23
  • 1
    this is parameters which you have to send send with url like ; www.xyz.com?name=dhaval&product_id=1&product_review=4. this is get method but if you want to use post method then you have to pass data in array same as i wrote in answer using nameValuePairs1 array. – Dhaval Parmar May 14 '12 at 07:26
  • this ***05-14 17:35:50.541: E/AndroidRuntime(1216): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.post/com.post.PostActivity}: android.os.NetworkOnMainThreadException** this is making my app crash and i have no idea how to resolve it help plzzz – Shoaib Ahmed May 14 '12 at 12:40
  • you added internet permission?? or put here you all logs which is give you error. add this two permition in your android manifest file. – Dhaval Parmar May 14 '12 at 12:43
  • see here for more details : http://blog.rajatpandit.com/2012/03/17/networkonmainthreadexception/ – Dhaval Parmar May 14 '12 at 12:58
  • 05-15 09:29:43.663: W/dalvikvm(572): threadid=1: thread exiting with uncaught exception (group=0x409c01f8) 05-15 09:29:43.683: E/AndroidRuntime(572): FATAL EXCEPTION: main 05-15 09:29:43.683: E/AndroidRuntime(572): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.post/com.post.PostActivity}: android.os.NetworkOnMainThreadException 05-15 09:29:43.683: E/AndroidRuntime(572): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956) – Shoaib Ahmed May 15 '12 at 04:31
  • 05-15 09:29:43.663: W/dalvikvm(572): threadid=1: thread exiting with uncaught exception (group=0x409c01f8) 05-15 09:29:43.683: E/AndroidRuntime(572): FATAL EXCEPTION: main 05-15 09:29:43.683: E/AndroidRuntime(572): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.post/com.post.PostActivity}: android.os.NetworkOnMainThreadException 05-15 09:29:43.683: E/AndroidRuntime(572): at – Shoaib Ahmed May 15 '12 at 04:32
  • android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956) 05-15 09:29:43.683: E/AndroidRuntime(572): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 05-15 09:29:43.683: E/AndroidRuntime(572): at android.app.ActivityThread.access$600(ActivityThread.java:123) 05-15 09:29:43.683: E/AndroidRuntime(572): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) – Shoaib Ahmed May 15 '12 at 04:33
1

Here is a function maybe you can use to post a string to a URL.

public String doHttpPost(final String fullUrl, final String body) {

        final URL url = new URL(fullUrl);

        final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        // set the request mode as POST
        urlConnection.setRequestMethod("POST");

        urlConnection.setUseCaches(false);
        urlConnection.setDoOutput(true);

        urlConnection.setRequestProperty("Accept-charset", "utf-8");
        urlConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");

        final DataOutputStream request = new DataOutputStream(urlConnection.getOutputStream());

        // write the body.
        request.writeBytes(body);

        // flush output buffer
        request.flush();
        request.close();

        // construct a read using input stream and charset.
        final InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream(), CHARSET_UTF8);
        final BufferedReader in = new BufferedReader(isr);

        String inputLine;
        final StringBuilder stringBuilder = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            stringBuilder.append(inputLine).append("\n");
        }

        in.close();
        isr.close();

        urlConnection.disconnect();

        return stringBuilder.toString(); 
}
Zephyr
  • 6,123
  • 34
  • 33