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関数をコーディングする最も簡単な方法は何ですか?サーバーを介して@GETで記述されたJSONObjectを取得するためだけに、AsyncTaskも追加機能も必要ありません。たとえば、コンソールに出力します。

4

1 に答える 1

1

RESTWebサービスを利用する方法

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 に答える