Java 如何获取HttpResponse文本

Java 如何获取HttpResponse文本,java,httpresponse,httpurlconnection,Java,Httpresponse,Httpurlconnection,我正在使用rest上载文件,并从服务器获得响应,如果上载成功(响应代码200),我还将获得此操作的guid,标头如下所示: HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Content-Type: text/plain;charset=ISO-8859-1 Content-Length: 36 Date: Wed, 26 Jun 2013 07:00:56 GMT **772fb809-61d5-4e12-b6f2-133f55ed9ac7** // th

我正在使用rest上载文件,并从服务器获得响应,如果上载成功(响应代码200),我还将获得此操作的guid,标头如下所示:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: text/plain;charset=ISO-8859-1
Content-Length: 36
Date: Wed, 26 Jun 2013 07:00:56 GMT

**772fb809-61d5-4e12-b6f2-133f55ed9ac7** // the guid
我在想我怎么才能拔出这个guid?我应该使用getInputStream()吗


10x

从您共享的响应中,您似乎得到的是正文中的guid,而不是标题中的guid。标题通常是名称-值对

您需要读取响应正文并获取guid。如果响应中只有guid,则可以执行以下操作:

URL url = new URL("http://yourwebserviceurl");
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
String encoding = con.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String guid = IOUtils.toString(in, encoding);
System.out.println(guid );

来自apache。

您可以使用一个
BufferedReader
,下面是一个示例:

InputStream inputStream = conn.getInputStream(); 
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); 
while(br.ready()){ 
    String line = br.readLine(); 
    //line has the contents returned by the inputStream 
}

你为什么不试着使用getInputStream,看看发生了什么事情,这似乎是标题,至少是正文的一部分?getinputstream().read()到字节数组,然后转换为字符串可能会有所帮助?@lgal您可以使用bufferedreader:
InputStream InputStream=conn.getinputstream();BufferedReader br=新的BufferedReader(新的InputStreamReader(inputStream));虽然(br.ready()){String line=br.readLine();//line包含inputStream返回的内容}
很棒,工作起来很有魅力:)请将其添加为答案,我将其标记为sulution@Igal您需要从导入apachejar