0

可能重复:
如何从服务器下载 JSON 的示例?

我已经阅读了很多教程,但仍然不清楚它是如何工作的。这是服务器端代码:

@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,例如打印到控制台。

4

1 回答 1

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;
}
于 2012-10-12T07:08:25.190 回答