OkHttp中的.string()和.toString()有什么区别?

4

我是OkHttp库的新手。 在使用这个库的过程中,我正在下载一个网页的源代码。 以下是我的代码:

Request request = new Request.Builder()
                    .url(urls[0])
                    .build();
try {
    Response response = okHttpClient.newCall(request).execute();
    source = response.body().toString();
    Log.i("ppp",source);
} catch (IOException e) {
    source =e.getMessage();
    e.printStackTrace();
}

但它向我显示了这个响应:

07-27 11:55:39.133 28050-28069/com.portonics.didar.okhttpdemo I/ppp: okhttp3.internal.http.RealResponseBody@420b639

但稍后只需将.toString()更改为.string()即可显示正确结果。
07-27 11:59:29.451 28050-31483/com.portonics.didar.okhttpdemo I/ppp: <!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for." name="description"><meta content="noodp" name="robots"><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><script>(function(){window.google={kEI:'JIF5WcLwC8Sd0gT1w6HIAQ',kEXPI:'1301798,1352823,1353383,1353801,1354231,1354277,1354562,1354570,1354619,1354625,1354838,3700277,3700347,3700433,3700442,4029815,4031109,4040138,4043492,4045840,4048347,4063220,4072777,4076999,4078430,4081038,4081164,4093313,4094544,4095910,4096463,4097153,4097922,4097929,4097951,4098721,4098728,4098752,4099391,4102237,4103475,4103845,4103861,4104258,4104658,4105085,4105113,4105241,4106626,4107555,4108124,4108498,4109316,4109490,4110259,4110404,4110656,4111016,4112542,4113148,4113216,4113495,4114597,4114975,4115697,4116365,4116926,4116935,4117280,4117406,4117534,4117912,4117980,4118103,4118227,4118280,4118475,4118626,4118798,4118976,4118977,4119032,4119034,4119036,4119272,4120004,4120046,4120058,4120195,4120278,4120289,4120508,4120578,4120646,4121035,4121036,4121209,4121278,4121316,4121515,4121852,4122007,4122048,4122705,4122724,4123335,4123994,4124100,4124288,10200083,10200096,16200027',authuser:0,kscs:'c9c918f0_24'};google.kHL='en';})();(function(){google.lc=[];google.li=0;google.getEI=function(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute("eid")));)a=a.parentNode;return b||google.kEI};google.getLEI=function(a){for(var b=null;a&&(!a.getAttribute||!(b=a.getAttribute("leid")));)a=a.parentNode;return b};google.https=function(){return"https:"==window.location.protocol};google.ml=function(){return null};google.wl=function(a,b){try{google.ml(Error(a),!1,b)}catch(c){}};google.time=function(){return(new Date).getTime()};google.log=function(a,b,c,d,g){if(a=google.logUrl(a,b,c,d,g)){b=new Image;var e=google.lc,f=google.li;e[f]=b;b.onerror=b.onload=b.onabort=function(){delete e[f]};google.vel&&google.vel.lu&&google.vel.lu(a);b.src=a;google.li=f+1}};google.logUrl=function(a,b,c,d,g){var e="",f=google.ls||"";c||-1!=b.search("&ei=")||(e="&ei="+google.getEI(d),-1==b.search("&lei=")&&(d=google.getLEI(d))&&(e+="&lei="+d));a=c||"/"+(g||"gen_204")+"?atyp=i&ct="+a+"&cad="+b+e+f+"&zx="+google.time();/^http:/i.test(a)&&google.https()&&(google.ml(Error("a"),!1,{src:a,glmm:1}),a="");return a};google.y={};google.x=function(a,b){if(a)var c=a.id;else{do c=Math.random();while(google.y[c])}google.y[c]=[a,b];return!1};google.lq=[];google.load=function(a,b,c){google.lq.push([[a],b,c])};google.loadAll=function(a,b){google.lq.push([a,b])};}).call(this);google.f={};var a=window.location,b=a.href.indexOf("#");if(0<=b){var c=a.href.substring(b+1);/(^|&)q=/.test(c)&&-1==c.indexOf("#")&&a.replace("/search?"+c.replace(/(^|&)fp=[^&]*/g,"")+"&cad=h")};</script><style>#gbar,#guser{font-size:13px;padding-top:1px !important;}#gbar{height:22px}#guser{padding-bottom:7px !important;text-align:right}.gbh,.gbd{border-top:1px solid #c9d7f1;font-size:1px}.gbh{height:0;position:absolute;top:24px;width:100%}@media all{.gb1{height:22px;margin-right:.5em;vertical-align:top}#gbar{float:left}}a.gb1,a.gb4{text-decoration:underline !important}a.gb1,a.gb4{color:#00c !important}.gbi .gb4{color:#dd8e27 !important}.gbf .gb4{color:#900 !important}
                                                                     </style><style>body,td,a,p,.h{font-family:arial,sans-serif}body{margin:0;overflow-y:scroll}#gog{padding:3px 8px 0}td{line-height:.8em}.gac_m td{line-height:17px}form{margin-bottom:20px}.h{color:#36c}.q{color:#00c}.ts td{padding:0}.ts{border-collapse:collapse}em{font-weight:bold;font-style:normal}.lst{height:25px;width:496px}.gsfi,.lst{font:18px arial,sans-serif}.gsfs{font:17px arial,sans-serif}.ds{display:inline-box;display:inline-block;margin:3px 0 4px;margin-left:4px}input{font-family:inherit}a.gb1,a.gb2,a.gb3,a.gb4{color:#11c !important

string()toString() 很容易混淆。 有人能告诉我为什么会出现这些问题以及这两种方法之间的区别吗?


你是在寻找这两种方法的区别吗? - sForSujit
1
toString() 方法是写在 Object 类中的,它是 Java 中每个类的父类,所以当我们不重写这个方法时,Java 内部会为一个对象创建一个哈希码并将其作为字符串返回。但是,当您调用 RealResponseBody 类定义的 string() 方法时,您将获得实际的响应。我希望这能够解决您的困惑。 - Mohammed Rampurawala
无关紧要:响应体必须关闭。请在此处阅读 https://square.github.io/okhttp/3.x/okhttp/okhttp3/ResponseBody.html。 - Eugen Pechanec
不是你的错。这是他们非常糟糕的设计。他们应该覆盖toString()以执行与string()相同的操作,或者干脆省略string() - user207421
4个回答

7

string()ResponseBody的一个方法,引用文档,它会:

返回使用Content-Type头的字符集解码的响应字符串。如果该头要么不存在要么没有字符集,则会尝试根据其BOM或UTF-8解码响应体。

toString()继承自java.lang.Object,并且没有被ResponseBody重写,因此它将返回默认实现(类似于okhttp3.ResponseBody@{some hash code})。


4

.toString():将对象以字符串形式返回。

.string():返回服务器响应的字符串格式。


1
.toString() Explanation :

如果你想将任何对象表示为字符串,就需要使用toString()方法。
toString()方法返回对象的字符串表示形式。
如果你打印任何对象,Java编译器会在对象上内部调用toString()方法。因此,重写toString()方法可以返回所需的输出,它可以是对象的状态等,具体取决于你的实现。
Java toString()方法的优点是,通过重写Object类的toString()方法,我们可以返回对象的值,因此不需要编写太多的代码。
string() Explanation :

在Java中,字符串基本上是表示字符值序列的对象。字符数组与Java字符串的工作方式相同。例如:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};  
String s=new String(ch); 

1

.toString():将对象转换为字符串格式。

.string():返回服务器响应的ResponseBody。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接