Android 在Logcat中打印输入流
我想在logcat中打印InputStream(用于测试/稍后我将使用它),我当前的代码如下Android 在Logcat中打印输入流,android,inputstream,Android,Inputstream,我想在logcat中打印InputStream(用于测试/稍后我将使用它),我当前的代码如下 @Override protected Void doInBackground(Void... params) { try { InputStream in = null; int response = -1; URL url = new URL(
@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;
}
@覆盖
受保护的Void doInBackground(Void…参数){
试一试{
InputStream in=null;
int响应=-1;
URL=新URL(
"http://any-website.com/search/users/sports+个人);
URLConnection conn=null;
HttpURLConnection httpConn=null;
conn=url.openConnection();
if(!(HttpURLConnection的连接实例))
抛出新IOException(“非HTTP连接”);
httpConn=(HttpURLConnection)conn;
httpConn.setAllowUserInteraction(假);
httpConn.setInstanceFollowRedirects(真);
httpConn.setRequestMethod(“GET”);
httpConn.connect();
response=httpConn.getResponseCode();
if(response==HttpURLConnection.HTTP\u OK){
in=httpConn.getInputStream();
}
if(in!=null){
Log.e(TAG,“>>>>打印您的标记应为常量,如:
public final String TAG = YourActivity.class.getSimpleName();
然后你会做一些类似的事情:
Log.e(TAG, "You're message here:", e)
e是打印堆栈中的错误
您还需要确保在Android库中导入日志
另外,在查看代码之后,您可能希望围绕httpConnection()展开
通过try/catch语句,您可以捕获错误,并将其放入日志文件中。如果您的流有内容或不为null,您可以打印日志,但您想知道是否没有连接,这将为您提供null值
希望有帮助
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());
在您的代码中:
Log.e(TAG, ">>>>>PRINTING<<<<<");
Log.e(TAG, in.toString());
Log.e(TAG, convertStreamToString(in));
Log.e(TAG,“>>>>>>>打印您的问题是什么,输入流为空?还是Log.e不工作?阅读本文:Log.e可能重复工作,我需要打印in@Caner您的链接很有用……但令人惊讶的是,我在搜索时没有将其作为搜索结果:(哦……我刚刚错过了,所以我想编辑该部分。实际上这不是问题……这回答了问题吗?另外,在日志中,我通常使用e.getmessage()
什么都没有发生……让我再次检查,如果不成功,我会再次给您打电话请确保!=null,logcat正在打印d日志和结果!=“”。此代码始终适用于Memy。此解决方案可能对某些人有所帮助:
Log.e(TAG, ">>>>>PRINTING<<<<<");
Log.e(TAG, in.toString());
Log.e(TAG, convertStreamToString(in));