2014-11-24 63 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