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文字列に保存しています。今、Json文字列をサーバーに送信したいのですが、どうすればよいでしょうか。提案してください。

4

7 に答える 7

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マニフェストファイルでインターネット許可を与えることを忘れないでください

詳細なチュートリアル: http://osamashabrez.com/client-server-communication-android-json/

于 2013-10-04T07:41:59.407 に答える
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 に答える
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 に答える
0

サーバー側の実装方法によって異なります 通常、データを送信するには、HTTPPost メソッドまたは HTTPPut メソッドが必要です。より一般的に使用されるのは、ヘッダー データと本文データを持つ HTTPPost メソッドです。

次の方法でそれを行う必要があります

1-jsonオブジェクトを文字列に変換します

user.toString();

2- ターゲット URL を追加

String URL="Enter URL here";

3-リクエストにURLを追加

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

応答は文字列 [ ] で、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

このコードが、データをサーバーに投稿してサーバーから結果を取得するのに役立つことを願っています-

// 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 に答える