2012-10-11 26 views
0

可能重複:
Example of how to download JSON from server?如何通過android訪問存儲在Tomcat服務器上的JSONObject?

我讀過不少教程,但它仍然不清楚它是如何工作的。這是服務器端代碼:

@GET 
@Produces(MediaType.APPLICATION_JSON) 
    public JSONObject respondAsReady() throws JSONException { 
      JSONObject json = new JSONObject(); 
      json.put("email", "email"); 
      json.put("szam", 5); 
      json.put("boolean", true); 
      return json; 
      } 

服務器端代碼:

public class GetJson extends Activity { 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.getjson_layout); 
    Button get=(Button)findViewById(R.id.get); 

    get.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) { 
      getMethod(); 
     } 
     }); 
    }} 

什麼是代碼實現getMethod功能最簡單的方法?我不需要任何AsyncTask,也不需要任何附加功能,只需通過服務器取回在@GET中編寫的JSONObject 例如,打印到控制檯。

回答

1

如何消耗REST Web服務

String url = "getserviceurl"; //如http://yourhost:8080/rest-ws/resources/admin/getCities

 String responseString =""; 

     final HttpGet httpGet = new HttpGet(url); 
     final DefaultHttpClient httpclient = new DefaultHttpClient(); 
     final HttpResponse response = httpclient.execute(httpGet); 
     final HttpEntity reponseEntity = response.getEntity(); 
     InputStream inputStream = reponseEntity.getContent(); 

     if (inputStream != null) 
     { 
      responseString = getStringFromInputStream(inputStream); 

     } 



// This will convert your inputStream into a String 
protected String getStringFromInputStream(InputStream inputStream) throws IOException 
{ 
    String responseString = null; 
    final StringBuilder stringBuilder = new StringBuilder(); 
    int ch; 

    while ((ch = inputStream.read()) != -1) 
    { 
     stringBuilder.append((char) ch); 
    } 

    responseString = stringBuilder.toString(); 

    return responseString; 
} 
相關問題