So it looks like your trying to connect to a server.... What remote
web services are you using.
For a scanner project I created last semester, I used XAMPP
locally(just to see code work correctly), then I used Teamviewer when
I went live.
On the remote server file, I placed a php file with the JSON object to
reference in the android code. Your code looks fine, however, I've
learn it's not just this code that you may need. I connected my code
using a button called my SQL... I'll post the code below... hope this
helps...
Also, something I didn't find out until the end, but make sure your
server PHP and code are up to date...I ran into a last minute issue I
had to correct on the server side...

This is the button code (click button, sends data to mySQL server from
anywhere)
 case R.id.buttonSQL1:

                try {

                        JSONObject json = new JSONObject();
                                json.put("barcode", mbarcodeEdit.getText());
                                json.put("description", description.getText());
                                json.put("make", make.getText());
                                json.put("serial", serial.getText());

                                HttpParams httpParams = new BasicHttpParams();
                                
HttpConnectionParams.setConnectionTimeout(httpParams,
                                                TIMEOUT_MILLISEC);
                                HttpConnectionParams.setSoTimeout(httpParams,
TIMEOUT_MILLISEC);
                                HttpClient client = new 
DefaultHttpClient(httpParams);

                                String url = 
"http://10.0.2.2:8080/webservice4.php";; //
needed for the php file pass over

                                HttpPost request = new HttpPost(url);
                                request.setEntity(new
ByteArrayEntity(json.toString().getBytes(
                                                "UTF8")));
                                request.setHeader("json", json.toString());
                                HttpResponse response = client.execute(request);
                                HttpEntity entity = response.getEntity();
                                // If the response does not enclose an entity, 
there is no
need
                                if (entity != null) {
                                        InputStream instream = 
entity.getContent();

                                        String result =
RestClient.convertStreamToString(instream);
                                        Log.i("Read from server", result);
                                        Toast.makeText(this,  result,
                                                        
Toast.LENGTH_LONG).show();
                                }
                        } catch (Throwable t) {
                                Toast.makeText(this, "Request failed: " + 
t.toString(),
                                                Toast.LENGTH_LONG).show();
                        }

               // showDialog(DIALOG_ID);

                break;
        }
    }

Also you need to insert this code (a separate java file called
RestClient)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
public class RestClient {

        public static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new
InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}


public static void connect(String url)
{

    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet(url);

    // Execute the request
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
        // Examine the response status
        Log.i("Praeda",response.getStatusLine().toString());

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no
need
        // to worry about connection release

        if (entity != null) {

            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            String result= convertStreamToString(instream);
            Log.i("Praeda",result);

            // A Simple JSONObject Creation
            JSONObject json=new JSONObject(result);
            Log.i("Praeda","<jsonobject>\n"+json.toString()+"\n</
jsonobject>");

            // A Simple JSONObject Parsing
            JSONArray nameArray=json.names();
            JSONArray valArray=json.toJSONArray(nameArray);
            for(int i=0;i<valArray.length();i++)
            {
                Log.i("Praeda","<jsonname"+i+">
\n"+nameArray.getString(i)+"\n</jsonname"+i+">\n"
                        +"<jsonvalue"+i+">\n"+valArray.getString(i)
+"\n</jsonvalue"+i+">");
            }

            // A Simple JSONObject Value Pushing
            json.put("sample key", "sample value");
            Log.i("Praeda","<jsonobject>\n"+json.toString()+"\n</
jsonobject>");

            // Closing the input stream will trigger connection
release
            instream.close();
        }


    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}

Remember to add your permissions in you xml Manifest file...

<uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.READ_PHONE_STATE" /
>


Here's an example of the PHP code I placed on my server...

<?php

$json = file_get_contents('php://input');

$obj = json_decode($json);

//echo $json;

$con = mysql_connect('localhost','Username','password')  or die
('Cannot connect to the DB');

mysql_select_db('tlmcqueen',$con);

  /* grab the posts from the db */
  //$query = "SELECT post_title, guid FROM wp_posts WHERE post_author
= $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT
$number_of_posts";

mysql_query("INSERT INTO `databasename`.`assets` (barcode,
description, make, serial)

VALUES ('".$obj->{'barcode'}."', '".$obj->{'description'}."','".$obj-
>{'make'}."','".$obj->{'serial'}."')");

mysql_close($con);
//

 //$posts = array($json);
  $posts = array(1);
    header('Content-type: application/json');
    echo json_encode(array('posts'=>$posts));

?>





On Feb 18, 2:09 pm, Mark Turkel <pbsdm...@gmail.com> wrote:
> Hi All,
>
> I have an IIS service (.net) that I'm obviously not passing the
> correct json message to.  I have tried many of the examples I have
> found on the web, but they all seem to point to PHP services.  I'm
> doing everything as everyone else is...and the json string looks as it
> should.  Can someone please let me know the big secret? :)  This
> should not take 2 days of my life to figure out... LOL!
>
> Thank in advance for your help!
> Mark Turkelhttp://www.PalmBeachSoftware.com
>
> Here's what I'm trying to post:
>
> String baseurlString = "http://MYSERVER.com/Service/SurfReport";;
>
>                JSONObject json = new JSONObject();
>                 try {
>                         json.put("UserID", 
> "00000000-0000-0000-0000-000000000001");
>                         json.put("City", "Boynton Beach");
>                         json.put("State", "FL");
>                         json.put("Country", "USA");
>                         json.put("Longitude", "-80.06643");
>                         json.put("Latitude", "26.525359");
>                         json.put("RptDate", "02/17/2012");
>                         json.put("WaveHeight", "3");
>                         json.put("ConditionID", "1");
>                         json.put("Comments", "Go get wet!");
>                 } catch (JSONException e) {
>                         // TODO Auto-generated catch block
>                         e.printStackTrace();
>                 }
>
> public void testPost(String baseurlString, final JSONObject json) {
>             try {
>
>                 HttpParams httpParams = new BasicHttpParams();
>                 HttpConnectionParams.setConnectionTimeout(httpParams,
> TIMEOUT_MILLISEC);
>                 HttpConnectionParams.setSoTimeout(httpParams,
> TIMEOUT_MILLISEC);
>                 HttpClient client = new DefaultHttpClient(httpParams);
>
>                 HttpPost request = new HttpPost(baseurlString);
>                 request.addHeader("Content-Type", "application/json;
> charset=utf-8");
>
>                 request.setEntity(new
> ByteArrayEntity(json.toString().getBytes("UTF8")));
>                 request.setHeader("json", json.toString());
>
>                 HttpResponse response = client.execute(request);
>                 HttpEntity entity = response.getEntity();
>
>                 // If the response does not enclose an entity, there
> is no need
>                 if (entity != null) {
>                     InputStream instream = entity.getContent();
>
>                     String result =
> RestClient.convertStreamToString(instream);
>                     Log.i("MARK","RESULT from server: " + result);
>                     Log.i("MARK", "sending surf report to:" + baseurlString +
> ":  " + request.getRequestLine()  + json.toString());
>
>                 }
>             } catch (Throwable t) {
>                 Toast.makeText(this, "Request failed: " + t.toString(),
> Toast.LENGTH_LONG).show();
>             }
>         }

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to