我正在尝试将 okhttpclient 与 okhttp3 一起使用,但它返回一个空值。
这是我的代码:
OkHttpClient client = new OkHttpClient();
HttpUrl.Builder urlBuilder = HttpUrl.parse("http://www.test.com/get_data.php").newBuilder();
urlBuilder.addEncodedQueryParameter("GroupName", groupName);
String url = urlBuilder.build().toString();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
String responseData = response.body().string();
JSONObject jsonObj = new JSONObject(responseData);
jArray = jsonObj.getJSONArray("result");
} catch (JSONException e) {
}
}
});
然后 responseData 返回 {"result":[]}
我尝试使用上面相同的 url,但使用不同的 httpClient 方法,它返回我想要的值,这里是 httpclient 代码:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.test.com/get_data.php");
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = httpclient.execute(httppost);
Log.i("postData", response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
StringBuilder sb = new StringBuilder();
String result = null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()), 65728);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
if(sb.toString().trim().length() > 0) {
result = sb.toString();
return result;
}
}
请帮助我,有 okhttp 经验的人,为什么我需要 okhttp ?因为 httpClient 在 sdk 23 中已经被弃用了,谢谢。