2013-10-04 57 views
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字符串發送到服務器我怎麼可能做到這一點請建議我。發送JSON字符串數據到服務器

+0

你需要發送數據的HTTPRequest方法有以下方法GET,POST,PUT,DELETE你如果您需要POST或PUT方法 –

回答

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

不要忘了給Internet權限在Android的manifest文件

詳細教程:http://osamashabrez.com/client-server-communication-android-json/

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 
} 
} 
0

它取決於您的服務器端如何實現 正常發送數據需要HTTPPost方法或HTTPPut方法。比較常用的是HTTPPost這有標題,你需要做的是在下面的方式

1-您的JSON對象轉換爲字符串

user.toString(); 

2-添加有針對性的URL

數據和身體數據

方法

String URL="Enter URL here"; 

3-添加URL請求

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

響應是字符串[]具有2索引 異用於響應代碼 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(); 
        } 
       } 
      } 
     } 

現在它的完成

1

的優選方法對於薑餅和according to Google是使用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對象

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); 
    } 
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()); 
    } 
相關問題