我有一个名为:ServiceCaller.java 的课程
此类包含一个用于调用 Web 服务的方法:
public static Response callService(String strURL, String Token, int timeout, Boolean isPostMethod) {
String error = "";
int statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
HttpURLConnection urlConnection = null;
try
{
URL url = new URL(strURL);
// Allow non trusted ssl certificates
if(strURL.startsWith("https"))
{
TrustManagerManipulator.allowAllSSL();
}
urlConnection = (HttpURLConnection) url.openConnection();
if (isPostMethod) {
urlConnection.setRequestMethod("POST");
}
else {
urlConnection.setRequestMethod("GET");
}
// Allow Inputs
urlConnection.setDoInput(true);
// Allow Outputs
urlConnection.setDoOutput(true);
// Don't use a cached copy.
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Token", Helpers.getUTF8Encode(Token));
urlConnection.setConnectTimeout(timeout);
DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());
dos.flush();
dos.close();
statusCode = urlConnection.getResponseCode();
Response r = new Response(statusCode, urlConnection.getInputStream(), "No Exception");
return r;
} catch (Exception ex) {
error = ex.getMessage();
if (error != null && !error.equals("") && error.contains("401"))
statusCode = HttpStatus.SC_UNAUTHORIZED;
} finally {
urlConnection.disconnect();
}
return new Response(statusCode, null, error);
}
这是响应类:
public static class Response
{
private int statusCode;
private InputStream responseStream;
private String exception;
public int getStatusCode() {
return statusCode;
}
public InputStream getResponseStream() {
return responseStream;
}
public String getExceptionError() {
return exception;
}
public Response(int code, InputStream stream, String strException)
{
this.statusCode = code;
this.responseStream = stream;
this.exception = strException;
}
}
这是我用来测试 ServiceCaller 中的函数的 Test 类:
public class TestDemo {
private static final String EncriptionKey = "keyValueToUse";
public static void main(String[] args) {
try {
String strURL = "http://...";
String strURL2 = "http://...";
String Token = "iTcakW5...";
int timeout = 120000;
Boolean isPostMethod = true;
ServiceCaller.Response resp = ServiceCaller.CallService(strURL2, Token, timeout, isPostMethod);
InputStream inputStream = resp.getResponseStream();
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer);
String resultJSON = writer.toString();
System.out.println("Status Code: " + resp.getStatusCode());
System.out.println("JSON String:\n" + resultJSON);
System.out.println("Exception: " + resp.getExceptionError());
} catch (Exception e) {
e.printStackTrace();
}
}
}
这是执行先前代码的输出:
Status Code: 200
JSON String:
Exception: No Exception
这是问题所在,在 Test 类中返回的 InputString 似乎是空的,因为转换为字符串会返回一个空字符串但是如果我执行相同的代码来转换 CallService 函数中的 InputString 则转换成功,还要注意正确返回状态代码和异常(字符串)。