0
我想获得HttpsURLConnection
POST请求的响应。 如果我尝试使用PostMan
来执行请求,我有一条消息作为回复(es: 1520)
。我必须保存这段代码,但我发现只读getResponseCode()
(200)或getResponseMessage()
(“OK”)的方法。我应该使用其他库?因为在HttpsUrlConnection
方法我没有找到什么有用的东西(https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html)获取POST请求的响应
我的代码是:
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setSSLSocketFactory(sslContext.getSocketFactory());
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "keep-alive");
con.setRequestProperty("Content-Type", w_AECONTYP);
con.setRequestProperty("Accept-Charset", w_AEACCCHA);
con.setRequestProperty("Accept-Encoding", w_AEACCENC);
StringBuilder postFile = new StringBuilder();
byte[] postFileBytes =w_FileToSend.getBytes("UTF-8");
con.setDoOutput(true);
try {
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(postFileBytes);
wr.flush();
wr.close();
} catch (Exception e) {
System.out.println("Connection Failed");
e.printStackTrace();
}
int responseCode = con.getResponseCode();
// get 200 code "OK"
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
但是,当在WHILE循环到达时,它不会在循环进入。 我该怎么做? 该文件采用JSON格式,但这不是问题。
我需要保存915码!
此代码产生200响应代码?我删除了DataOutputStream的东西,它似乎为我工作,只要url不重定向。 –
是产生200代码。还有另一个消息,我需要..但在while((inputLine = in.readLine())!= null)in.readLine为null! – Simone
你确定你传递了正确的URL,并且需要任何头文件(如果有) URL obj = new URL(url);\t \t HttpsURLConnection con =(HttpsURLConnection)obj.openConnection(); – kuhajeyan