我想在logcat中打印InputStream(用于测试/稍后我将使用它),我目前的代码如下。
@Override
protected Void doInBackground(Void... params) {
try {
InputStream in = null;
int response = -1;
URL url = new URL(
"http://any-website.com/search/users/sports+persons");
URLConnection conn = null;
HttpURLConnection httpConn = null;
conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
if (in != null) {
Log.e(TAG, ">>>>>PRINTING<<<<<");
Log.e(TAG, in.toString());
// TODO: print 'in' from here
}
in.close();
in = null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
但是我无法做到这一点,所以请检查代码并添加/修改代码来执行此操作。
答案 0 :(得分:10)
String convertStreamToString(java.io.InputStream is) {
try {
return new java.util.Scanner(is).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
在您的代码中:
Log.e(TAG, ">>>>>PRINTING<<<<<");
Log.e(TAG, in.toString());
Log.e(TAG, convertStreamToString(in));
答案 1 :(得分:0)
你的TAG
应该是一个常数:
public final String TAG = YourActivity.class.getSimpleName();
然后你会做类似的事情:
Log.e(TAG, "You're message here:", e)
e是来自打印堆栈的错误。
您还需要确保导入登录Android库。
此外,在查看代码之后,您可能希望用try / catch语句包围httpConnection()
,这样您就可以捕获错误,并将其放入日志文件中。如果你的流有东西,或者不是null,你有日志打印,但你想知道你是否没有连接,这会给你一个空值。
希望有所帮助。
答案 2 :(得分:0)
Just add this code to if(in != null):
byte[] reqBuffer = new byte[1024];
int reqLen = 1024;
int read = -1;
StringBuilder result = new StringBuilder();
try {
while ((read = is.read(reqBuffer, 0, reqLen)) >= 0)
result.append(new String(reqBuffer, 0, read));
} catch (IOException e) {
e.printStackTrace();
}
Log.d("TAG", result.toString());