我想要一个JSON,但我得到一个响应头。我使用的是Android Studio 2.1.1。我正在使用OkHttpClient
库和AsyncTask
将它与主线程分开。
public class MainActivity extends AppCompatActivity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
new PostTask().execute("url");
}
private class PostTask extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
String url = params[0];
// Dummy code
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(1, TimeUnit.MINUTES); // connect timeout
client.setReadTimeout(1, TimeUnit.MINUTES); // socket timeout
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "data=something");
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("cache-control", "no-cache")
.addHeader("postman-token", "7a4d5df8-5aed-19bf-e1fb-c85f821c1d10")
.addHeader("content-type", "application/x-www-form-urlencoded")
.build();
Response response = null;
try {
response = client.newCall(request).execute();
return response.toString();
} catch (Exception e1) {
e1.printStackTrace();
return e1.toString();
}
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tv.setText(result);
}
}
}
答案 0 :(得分:1)
你需要请求身体。
而不是使用:
return response.toString();
使用:
return response.body().string();
可以归还身体内容。
注意: .toString()方法返回对象字符串。
这里有一个文档示例:http://square.github.io/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();
}