1
 String Person_Name=et1.getText().toString();
 String Mobile_Number=et2.getText().toString();
 String Person_Query=et3.getText().toString();
 String Action=et4.getText().toString();

try
{
    JSONObject action=new JSONObject();
    JSONObject user=new JSONObject();
    action.put("person_name", Person_Name);
    action.put("mobile_number", Mobile_Number);
    action.put("person_query", Person_Query);
    action.put("action", Action);
    user.put("result",action);


     jsonString1 =user.toString();
}
catch (Exception je)
{

}

在这里,我正在收集我的所有数据并存储在 json String 现在我想将 Json String 发送到服务器我该怎么做请建议我。

4

7 回答 7

1

根据 Google,Gingerbread 及更高版本的首选方法是使用HttpURLConnection(而不是DefaultHttpClient)。

    URL url = new URL("http://www.example.com/api/whatever");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    // Allow Outputs (sending)
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Enable POST method
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Content-Type", "application/json");

    connection.setRequestProperty("charset", "utf-8");

    DataOutputStream printout = new DataOutputStream(connection.getOutputStream());
    printout.write(json.toString().getBytes("UTF8"));

    printout.flush();
    printout.close();

json你的 json 对象在哪里

于 2013-10-04T07:54:06.493 回答
1

尝试这样的事情

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppostreq = new HttpPost(wurl);
StringEntity se = new StringEntity(jsonobj.toString());
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
httppostreq.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppostreq);

不要忘记在 Android Manifest 文件中授予Internet 权限

详细教程: http: //osamashabrez.com/client-server-communication-android-json/

于 2013-10-04T07:41:59.407 回答
0

希望此代码可以帮助您将数据发布到服务器并从服务器获取结果-

// Sending HTTPs Requet to Server

    try {
        Log.v("GG", "Sending sever 1 - try");
        // start - line is for sever connection/communication
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "10.0.0.1/abc.php");

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("qrcode", contents));


        httppost.setEntity(new UrlEncodedFormEntity(
                nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        // end - line is for sever connection/communication
        InputStream is = entity.getContent();

        Toast.makeText(getApplicationContext(),
                "Send to server and inserted into mysql Successfully", Toast.LENGTH_LONG)
                .show();

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

        entity = response.getEntity();
        String getResult = EntityUtils.toString(entity);
        Log.e("response =", " " + getResult);



    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection "
                + e.toString());
    }
于 2014-01-22T09:09:04.933 回答
0

最好的方法是使用 JSONStringer 类并使用键值对发送数据。

 HttpPost request = new HttpPost(your URL);
 request.setHeader("Accept", "application/json");
 request.setHeader("Content-type", "application/json");

 JSONStringer vm;
 try {
        vm = new JSONStringer().object().key("person_name").value(Person_Name)
        .key("mobile_number").value(Mobile_Number)
        .key("person_query").value(Person_Query)
        .key("action").value(Action).endObject();
        StringEntity entity = new StringEntity(vm.toString());
        request.setEntity(entity);
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(request);
     }
于 2013-10-04T07:57:33.530 回答
0

它取决于您的服务器端如何实现 通常发送数据需要 HTTPPost 方法或 HTTPPut 方法。更常用的是具有标头数据和正文数据的 HTTPPost 方法

您需要按以下方式进行

1-将您的 json 对象转换为字符串

user.toString();

2-添加目标网址

String URL="Enter URL here";

3-将url添加到请求中

response = dohttpPostWithCode(URL.toString(),user.toString());

response 是 String [ ],它有 2 个索引 i- 用于响应代码 ii- 用于数据

4-处理数据的方法

     public String[] dohttpPostWithCode(String url,String postParameters ) throws Exception {
         URL weburl = new URL(url);
         URI uri = new URI(weburl.getProtocol(), weburl.getUserInfo(), weburl.getHost(), weburl.getPort(), weburl.getPath(), weburl.getQuery(), weburl.getRef());
            BufferedReader in = null;
            String[] result = new String[2];         
            try {
                 HttpParams httpParameters = new BasicHttpParams();
                // Set the timeout in milliseconds until a connection is established.
                int timeoutConnection = 20000;
                HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                // Set the default socket timeout (SO_TIMEOUT) 
                // in milliseconds which is the timeout for waiting for data.
                int timeoutSocket = 20000;
                HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
                HttpURLConnection httpURL=(HttpURLConnection) weburl.openConnection();
                httpURL.setDoOutput(true);
                httpURL.setDoInput(true);
                httpURL.setRequestMethod("POST");
                HttpClient client =new  DefaultHttpClient(httpParameters);            
                HttpPost httpPost = new HttpPost(uri);
                //httpPost.addHeader("language","en");
                httpPost.addHeader("Content-Type",  "application/json");

               // StringEntity entity = new StringEntity(postParameters, HTTP.UTF_8);
                httpPost.setEntity(new StringEntity(postParameters));
               // httpPost.setEntity(entity);
               // httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
                HttpResponse response = client.execute(httpPost);               
                in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuffer sb = new StringBuffer("");
                String line = "";
                String NL = System.getProperty("line.separator");

                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }
                in.close();
/*              String result = sb.toString();
                return result;*/
                result[0] = response.getStatusLine().getStatusCode()+"";
                result[1] = sb.toString();
                return result;
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

现在它完成了

于 2013-10-04T07:49:56.333 回答
0
public void postData() {
   // Create a new HttpClient and Post Header
   HttpClient httpclient = new DefaultHttpClient();
   HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
    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
}
} 
于 2013-10-04T07:43:39.710 回答
0

尝试这个

HttpPost httppost = new HttpPost("your link");
httppost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(user.toString()); 
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se); 

HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
于 2013-10-04T07:40:31.957 回答