Java OkHttp 如何获取 Json 字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28221555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:49:06  来源:igfitidea点击:

How does OkHttp get Json string?

javahttpokhttpembedded-jetty

提问by Haifeng Zhang

Solution: It was a mistake on my side.

解决方案:这是我的错误。

The right way is response.body().string()other than response.body.toString()

正确的方法是response.body().string()而不是response.body.toString()

Im using Jetty servlet, the URL ishttp://172.16.10.126:8789/test/path/jsonpage, every time request this URL it will return

我使用 Jetty servlet,URL 是http://172.16.10.126:8789/test/path/jsonpage,每次请求这个 URL 都会返回

{"employees":[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

It shows up when type the url into a browser, unfortunately it shows kind of memory address other than the json string when I request with Okhttp.

它在浏览器中输入 url 时显示,不幸的是,当我使用Okhttp.

TestActivity﹕ com.squareup.okhttp.internal.http.RealResponseBody@537a7f84

The Okhttp code Im using:

我使用的 Okhttp 代码:

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();
  return response.body().string();
}

Can anyone helpe?

任何人都可以帮忙吗?

采纳答案by Newbies

try {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
        .url(urls[0])
        .build();
    Response responses = null;

    try {
        responses = client.newCall(request).execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
    String jsonData = responses.body().string();
    JSONObject Jobject = new JSONObject(jsonData);
    JSONArray Jarray = Jobject.getJSONArray("employees");

    for (int i = 0; i < Jarray.length(); i++) {
        JSONObject object     = Jarray.getJSONObject(i);
    }
}

Example add to your columns:

示例添加到您的列:

JCol employees  = new employees();
colums.Setid(object.getInt("firstName"));
columnlist.add(lastName);           

回答by Phillip Kigenyi

I hope you managed to obtain the json data from the json string.

我希望您设法从 json 字符串中获取 json 数据。

Well I think this will be of help

好吧,我认为这会有所帮助

try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
    .url(urls[0])
    .build();
Response responses = null;

try {
    responses = client.newCall(request).execute();
} catch (IOException e) {
    e.printStackTrace();
}   

String jsonData = responses.body().string();

JSONObject Jobject = new JSONObject(jsonData);
JSONArray Jarray = Jobject.getJSONArray("employees");

//define the strings that will temporary store the data
String fname,lname;

//get the length of the json array
int limit = Jarray.length()

//datastore array of size limit
String dataStore[] = new String[limit];

for (int i = 0; i < limit; i++) {
    JSONObject object     = Jarray.getJSONObject(i);

    fname = object.getString("firstName");
    lname = object.getString("lastName");

    Log.d("JSON DATA", fname + " ## " + lname);

    //store the data into the array
    dataStore[i] = fname + " ## " + lname;
}

//prove that the data was stored in the array      
 for (String content ; dataStore ) {
        Log.d("ARRAY CONTENT", content);
    }

Remember to use AsyncTask or SyncAdapter(IntentService), to prevent getting a NetworkOnMainThreadException

请记住使用 AsyncTask 或 SyncAdapter(IntentService),以防止出现 NetworkOnMainThreadException

Also import the okhttp library in your build.gradle

还要在 build.gradle 中导入 okhttp 库

compile 'com.squareup.okhttp:okhttp:2.4.0'

compile 'com.squareup.okhttp:okhttp:2.4.0'

回答by Venkat Veeravalli

I am also faced the same issue

我也面临同样的问题

use this code:

使用此代码:

// notice string() call
String resStr = response.body().string().toString();    
JSONObject json = new JSONObject(resStr);

it definitely works

它绝对有效

回答by Kuldip Sharma

As I observed in my code. If once the value is fetched of body from Response, its become blank.

正如我在我的代码中观察到的那样。如果一旦从 Response 中获取了 body 的值,它就会变成空白。

String str = response.body().string();  // {response:[]}

String str1  = response.body().string();  // BLANK

So I believe after fetching once the value from body, it become empty.

所以我相信从 body 中获取一次值后,它就会变成空的。

Suggestion : Store it in String, that can be used many time.

建议:存放在String中,可以多次使用。

回答by Deven

Below code is for getting data from online server using GET method and okHTTP library for android kotlin...

下面的代码用于使用 GET 方法和 android kotlin 的 okHTTP 库从在线服务器获取数据...

Log.e("Main",response.body!!.string())

Log.e("Main", response.body!!.string())

in above line !! is the thing using which you can get the json from response body

在上面那一行!!是使用它可以从响应正文中获取 json 的东西

val client = OkHttpClient()
            val request: Request = Request.Builder()
                .get()
                .url("http://172.16.10.126:8789/test/path/jsonpage")
                .addHeader("", "")
                .addHeader("", "")
                .build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    // Handle this
                    Log.e("Main","Try again latter!!!")
                }

                override fun onResponse(call: Call, response: Response) {
                    // Handle this
                    Log.e("Main",response.body!!.string())
                }
            })