【问题标题】:How can I reach the JSONObject stored on Tomcat server via android? [duplicate]如何通过 android 访问存储在 Tomcat 服务器上的 JSONObject? [复制]
【发布时间】:2012-10-11 00:24:50
【问题描述】:

可能重复:
Example of how to download JSON from server?

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

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

【问题讨论】:

    标签: android json jersey httpclient http-get


    【解决方案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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-10
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 2018-08-19
      • 2016-09-09
      • 2016-01-03
      • 1970-01-01
      相关资源
      最近更新 更多