[英]Get the Response from POST request
I would like to obtain the response from a HttpsURLConnection
POST request. 我想从
HttpsURLConnection
POST请求获取响应。 If I try to do the request with PostMan
, I have one message as response (es: 1520)
. 如果我尝试通过
PostMan
发出请求, PostMan
有一条消息作为响应(es: 1520)
。 I have to save this code, but I find the method for read just the getResponseCode()
(200) or getResponseMessage()
("OK"). 我必须保存此代码,但是我找到了只读取
getResponseCode()
(200)或getResponseMessage()
(“ OK”)的方法。 I should use another libraries? 我应该使用另一个库吗? Because in the
HttpsUrlConnection
method I don't find anything useful ( https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html ) 因为在
HttpsUrlConnection
方法中我找不到任何有用的东西( https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html )
My code is: 我的代码是:
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();
But when arrived at the WHILE loop, it doesn't enter in the cycle. 但是,到达WHILE循环时,它不会进入循环。 How I can do this?
我该怎么做? The file is in JSON format, but that isn't the problem.
该文件为JSON格式,但这不是问题。
I need to save that 915 code!! 我需要保存915代码!
You could use HttpResponse
and HttpPost
for getting a response from server (as well as the Response Code): 您可以使用
HttpResponse
和HttpPost
从服务器获取响应(以及响应代码):
HttpResponse httpResponse = httpClient.execute(new HttpPost(URL));
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
// now response is in the stringBuilder.toString()
I hope this will help you. 我希望这能帮到您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.