我无法理解为什么Java HttpURLConnection不遵循重定向.我使用以下代码来获取此页面:
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.InputStream;
public class Tester {
public static void main(String argv[]) throws Exception{
InputStream is = null;
try {
String httpUrl = "http://httpstat.us/301";
URL resourceUrl = new URL(httpUrl);
HttpURLConnection conn = (HttpURLConnection)resourceUrl.openConnection();
conn.setConnectTimeout(15000);
conn.setReadTimeout(15000);
conn.connect();
is = conn.getInputStream();
System.out.println("Original URL: "+httpUrl);
System.out.println("Connected to: "+conn.getURL());
System.out.println("HTTP response code received: "+conn.getResponseCode());
System.out.println("HTTP response message received: "+conn.getResponseMessage());
} finally {
if (is != null) is.close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
而且,我收到以下回复(看起来绝对正确!):
Original URL: http://httpstat.us/301 Connected to: …
如果服务器返回错误,我在检索Json响应时遇到问题.详情见下文.
我用java.net.HttpURLConnection.我设置了请求属性,然后我做:
conn = (HttpURLConnection) url.openConnection();
Run Code Online (Sandbox Code Playgroud)
在那之后,当请求成功时,我得到了Json的回复:
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
}
return sb.toString();
Run Code Online (Sandbox Code Playgroud)
当服务器返回50x或40x之类的错误时,我无法检索收到的Json.以下行抛出IOException:
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
// throws java.io.IOException: Server returned HTTP response code: 401 for URL: www.example.com
Run Code Online (Sandbox Code Playgroud)
服务器确定发送正文,我在外部工具Burp Suite中看到它:
HTTP/1.1 401 Unauthorized
{"type":"AuthApiException","message":"AuthApiException","errors":[{"field":"email","message":"Invalid username and/or password."}]}
Run Code Online (Sandbox Code Playgroud)
我可以使用以下方法获得响应消息(即"内部服务器错误")和代码(即"500"):
conn.getResponseMessage();
conn.getResponseCode();
Run Code Online (Sandbox Code Playgroud)
但我无法检索请求正文...也许有一些方法我没有在库中注意到?
在Java中,当HTTP结果为404范围时,此代码抛出异常:
URL url = new URL("http://stackoverflow.com/asdf404notfound");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.getInputStream(); // throws!
Run Code Online (Sandbox Code Playgroud)
在我的情况下,我碰巧知道内容是404,但我仍然想要阅读回复的主体.
(在我的实际情况中,响应代码是403,但响应正文解释了拒绝的原因,我想将其显示给用户.)
我如何访问响应正文?
我在从我的应用程序中下载二进制文件(视频)时遇到问题.在Quicktime中,如果我直接下载它可以正常工作但通过我的应用程序不知何故它搞砸了(即使它们在文本编辑器中看起来完全相同).这是一个例子:
URL u = new URL("http://www.path.to/a.mp4?video");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(root,"Video.mp4"));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) > 0 ) {
f.write(buffer);
}
f.close();
Run Code Online (Sandbox Code Playgroud) 我对android开发比较陌生.我正在开发一个Android应用程序,我正在向Web服务器发送请求并解析json对象.我经常java.net.SocketTimeoutException: Connection timed out在与服务器通信时遇到异常.有时它会毫无问题地完美运行.我知道这个问题在很多时候都被提出过.但我仍然没有得到任何满意的解决方案来解决这个问题.我正在下面发布我的logcat和app-server通信代码.
public JSONObject RequestWithHttpUrlConn(String _url, String param){
HttpURLConnection con = null;
URL url;
String response = "";
Scanner inStream = null;
PrintWriter out = null;
try {
url = new URL(_url);
con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
if(param != null){
con.setFixedLengthStreamingMode(param.getBytes().length);
}
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
out = new PrintWriter(con.getOutputStream());
if(param != null){
out.print(param);
}
out.flush();
out.close();
inStream = new Scanner(con.getInputStream());
while(inStream.hasNextLine()){
response+=(inStream.nextLine());
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch …Run Code Online (Sandbox Code Playgroud) 当我尝试使用非标准的HTTP方法,如PATCH和URLConnection:
HttpURLConnection conn = (HttpURLConnection) new URL("http://example.com").openConnection();
conn.setRequestMethod("PATCH");
Run Code Online (Sandbox Code Playgroud)
我得到一个例外:
java.net.ProtocolException: Invalid HTTP method: PATCH
at java.net.HttpURLConnection.setRequestMethod(HttpURLConnection.java:440)
Run Code Online (Sandbox Code Playgroud)
使用像Jersey这样的更高级别的API会产生相同的错误.是否有解决方法来发出PATCH HTTP请求?
我正在用HttpURLConnectionJava中的对象做基本的http auth .
URL urlUse = new URL(url);
HttpURLConnection conn = null;
conn = (HttpURLConnection) urlUse.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-length", "0");
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setConnectTimeout(timeout);
conn.setReadTimeout(timeout);
conn.connect();
if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
{
success = true;
}
Run Code Online (Sandbox Code Playgroud)
我期待一个JSON对象,或者是有效JSON对象格式的字符串数据,或者是带有简单明文的HTML,它是有效的JSON.如何从HttpURLConnection返回响应后访问它?
我已经创建了HTTPUrlConnection:
String postData = "x=val1&y=val2";
URL url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Set-Cookie", sessionCookie);
conn.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length));
// How to add postData as http body?
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
Run Code Online (Sandbox Code Playgroud)
我不知道如何在http体中设置postData.怎么办?我会更好地使用HttpPost吗?
谢谢你的帮助.
有没有办法检查InputStream是否已被gzip压缩?这是代码:
public static InputStream decompressStream(InputStream input) {
try {
GZIPInputStream gs = new GZIPInputStream(input);
return gs;
} catch (IOException e) {
logger.info("Input stream not in the GZIP format, using standard format");
return input;
}
}
Run Code Online (Sandbox Code Playgroud)
我试过这种方式,但它没有按预期工作 - 从流中读取的值无效.编辑:添加了我用来压缩数据的方法:
public static byte[] compress(byte[] content) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
GZIPOutputStream gs = new GZIPOutputStream(baos);
gs.write(content);
gs.close();
} catch (IOException e) {
logger.error("Fatal error occured while compressing data");
throw new RuntimeException(e);
}
double ratio = (1.0f * content.length / …Run Code Online (Sandbox Code Playgroud) 你知道如何设置Content-Type的HttpURLConnection的?
以下代码在Blackberry上,我想要Android等价:
connection.setRequestProperty("content-type", "text/plain; charset=utf-8");
connection.setRequestProperty("Host", "192.168.1.36");
connection.setRequestProperty("Expect", "100-continue");
Run Code Online (Sandbox Code Playgroud)
它适合Android吗?
请指教.