2014-11-24 71 views
-1

web服務我想JSON對象傳遞給Web服務這樣的如何發佈JSON對象像URL

firstname=jhon&lastname=mic&[email protected]&sex=M&hometown=blablabla 

如何傳遞,任何一個請幫助me.Am試圖這樣

JSONObject json = new JSONObject(); 
     json.put("firstname", firstname); 
     json.put("lastname", laststname); 
     json.put("mail", mail); 
     json.put("sex", sex); 
     json.put("hometown", hometown) 


    HttpClient client=new DefaultHttpClient(); 

     HttpPost post=new HttpPost(url); 
     post.setEntity(new ByteArrayEntity(json1.toString().getBytes("UTF8")));   
     HttpResponse response = client.execute(post);  

     HttpEntity entity = response.getEntity(); 
     if(entity!=null) 
     { 
      InputStream instream=entity.getContent(); 
      String result=convertStreamToString(instream); 

     } 

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

但這個代碼不貼權值的web服務,請問有什麼錯了,請幫助我,
謝謝:)

+1

'firstname = jhon&lastname = mic&mail = jhon @ gmail.com&sex = M&hometown = blablabla'不是JSON,它是'application/x-www-form-urlencoded' ......在網上也有很多類似的問題,在線涵蓋這個問題的教程 – Selvin 2014-11-24 11:25:01

+0

哦謝謝你,我不知道。請告訴我它是如何發佈到web服務 – user3814997 2014-11-24 11:29:26

+0

@謝爾文:謝謝你,我的問題解決了。如果不這樣說,我浪費了我的整個一天。謝謝你許多 – user3814997 2014-11-24 12:10:01

回答

0
StringBuilder bu = new StringBuilder(); 
    for(int i = 0; i<json.names().length(); i++){ 
     bu.append("&"); 
     try { 
      bu.append(json.names().getString(i)+"="+json.get(json.names().getString(i))); 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
    bu.toString();//give you parameters