try { InputStream is = socket.getInputStream(); char pre='a';char cur='a'; StringBuilder sb = new StringBuilder(); int in; while ((in=is.read()) !=-1){ cur=(char)in; if (pre==13 && cur==10){ break; } sb.append(cur); pre=cur; } String line = sb.toString().trim(); System.out.println("头:"+line); } catch (IOException e) { e.printStackTrace(); }帮我把line字符串截取三段
时间: 2024-01-18 19:01:56 浏览: 33
假设line字符串的格式为:`GET /index.html HTTP/1.1`,则可按照空格进行分割,代码如下:
```
String[] segments = line.split(" ");
if (segments.length >= 3) {
String method = segments[0]; // GET
String path = segments[1]; // /index.html
String protocol = segments[2]; // HTTP/1.1
}
```
其中,`method`代表请求方法,`path`代表请求路径,`protocol`代表协议版本。
相关问题
andriod 5 InputStream inputStream = conn.getInputStream();报错
根据提供的引用内容,可以看出在Android 5中使用`InputStream inputStream = conn.getInputStream();`会报错。这可能是因为在Android 5中,网络请求需要在子线程中执行,而不能在主线程中执行。因此,你需要将网络请求放在一个异步任务中执行,以避免报错。
以下是一个示例代码,展示了如何在Android 5中正确地使用`InputStream`获取网络数据:
```java
// 在主线程中创建异步任务
new AsyncTask<Void, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(Void... params) {
try {
// 在子线程中执行网络请求
URL url = new URL("http://example.com/image.jpg"); HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
// 获取输入流并解码为Bitmap
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
// 关闭输入流
is.close();
// 返回Bitmap
return bitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(Bitmap bitmap) {
// 在主线程中更新UI,将Bitmap显示在ImageView中
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
}
}
}.execute();
```
请注意,上述代码中的`imageView`是一个`ImageView`实例,用于显示获取到的图片。你需要将其替换为你自己的`ImageView`实例。
android 5 InputStream inputStream = conn.getInputStream(); 报错
在Android 5中,`conn.getInputStream()`方法可能会抛出`IOException`异常。因此,在使用`InputStream`时,需要在代码中进行异常处理。
以下是一个示例代码,演示了如何在Android 5中处理`InputStream`的异常:
```java
try {
InputStream inputStream = conn.getInputStream();
// 处理输入流
// ...
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
// 处理异常
// ...
}
```
在上述代码中,我们使用了`try-catch`语句块来捕获可能抛出的`IOException`异常。在`try`块中,我们获取了`InputStream`并进行处理。在`catch`块中,我们打印了异常的堆栈信息,并可以进行相应的异常处理操作。