我尝试制作一个可以从智能手机获取图像的Java程序。我成功地使用URLConnection连接到应用程序的Web服务器并获取一些数据,但问题是当我将图像写入文件时,当我用程序打开它时,该文件似乎已损坏。我已经看到数据是MJPEG格式的,我需要用某些东西解码它还是这只是数据检索的一个问题?
这是我的代码:
package fr.paragoumba.streamingdisplay;
import java.io.*;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
Test mp = new Test("http://192.168.1.19:8080/video", null, null);
}
public Test(String mjpeg_url, String username, String password)
{
int imageCount = 0;
try {
if (username != null && password != null)
{
Authenticator.setDefault(new HTTPAuthenticator(username, password));
}
File file = new File("D:/Desktop/Dev/Out/images/image" + System.currentTimeMillis() + ".jpg");
boolean firstImage = true;
if (!file.exists()) file.createNewFile();
URL url = new URL(mjpeg_url);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
int lineCount = 0;
boolean lineCountStart = false;
boolean saveImage = false;
while ((inputLine = in.readLine()) != null) {
//File image = new File("D:/Desktop/Dev/Out/images/image" + imageCount + ".jpeg");
// Should be checking just for "--" probably
if (inputLine.lastIndexOf("--Ba4oTvQMY8ew04N8dcnM") > -1)
{
// Got an image boundary, stop last image
// Start counting lines to get past:
// Content-Type: image/jpeg
// Content-Length: 22517
saveImage = false;
lineCountStart = true;
System.out.println("Got a new boundary");
System.out.println(inputLine);
if (!firstImage) System.exit(0);
}
else if (lineCountStart)
{
lineCount++;
if (lineCount >= 2)
{
lineCount = 0;
lineCountStart = false;
imageCount++;
saveImage = true;
System.out.println("Starting a new image");
firstImage = !firstImage;
//if (!image.exists()) image.createNewFile();
}
}
else if (saveImage)
{
System.out.println("Saving an image line: " + inputLine);
/*try(PrintWriter pw = new PrintWriter(file)){
pw.print(inputLine);
}*/
try(FileOutputStream fos = new FileOutputStream(file)){
fos.write(inputLine.getBytes());
}
}
else {
System.out.println("What's this:");
System.out.println(inputLine);
}
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static class HTTPAuthenticator extends Authenticator {
private String username, password;
public HTTPAuthenticator(String user, String pass) {
username = user;
password = pass;
}
protected PasswordAuthentication getPasswordAuthentication() {
System.out.println("Requesting Host : " + getRequestingHost());
System.out.println("Requesting Port : " + getRequestingPort());
System.out.println("Requesting Prompt : " + getRequestingPrompt());
System.out.println("Requesting Protocol: " + getRequestingProtocol());
System.out.println("Requesting Scheme : " + getRequestingScheme());
System.out.println("Requesting Site : " + getRequestingSite());
return new PasswordAuthentication(username, password.toCharArray());
}
}
}
感谢您的帮助