#java #http
#java #http
Вопрос:
У меня есть Java-приложение, которое выполняет HTTP-УДАЛЕНИЕ во внешнюю службу REST. Эта ошибка возвращается ко мне с сервера (работает на C #):
"Value cannot be null.rnParameter name: sourcen at System.Linq.Enumerable.Count[TSource](IEnumerable`1 source)rn at AppCloud_Framework.Controllers.NotificationItemsController.DeleteNotificationItem(NotificationItem[] notificationItems) in C:\Users\jonas\OneDrive\VS Projects\AppCloud Framework\AppCloud Framework\Controllers\NotificationItemsController.cs:line 101nValue:null"
Дело в том, что когда я настраиваю Postman для отправки HTTP-запроса на тот же URL-адрес, с той же полезной нагрузкой и тем же методом HTTP, действие выполняется успешно.
У меня нет доступа к серверу для дальнейшего расследования, поэтому мне нужно найти разрешение со стороны клиента. В любом случае, похоже, это проблема на стороне клиента.
Я пытался сам найти проблему, но безуспешно. Все, что я мог придумать, это добавить «application / json» для принятия и свойств заголовка Content-Type.
Мой HTTP-клиент:
public static Response execute(String url, Method method, String body) {
Response response = new Response();
try {
////////////////////////////////////////
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
// Install the all-trusting trust manager
final SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
////////////////////////////////////////
URL urlObj = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) urlObj.openConnection();
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod(method.toString());
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
//conn.setRequestProperty("Authorization", _authToken);
if (method == Method.POST || method == Method.PUT || method == Method.DELETE) {
conn.setDoOutput(true);
final OutputStream os = conn.getOutputStream();
os.write(body.getBytes());
os.flush();
os.close();
}
int status = conn.getResponseCode();
//log.info("HTTP request status code: " status);
InputStream is;
if (status>399){
is = conn.getErrorStream();
}else{
is = conn.getInputStream();
}
if (is==null) return null;
BufferedReader rd = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
String line;
while ((line = rd.readLine()) != null) {
response.body = line;
}
rd.close();
response.statusCode = conn.getResponseCode();
conn.disconnect();
} catch (Exception e) {
//log.error(e.getMessage());
e.printStackTrace();
System.out.println("");
response.exception = e.getMessage();
}
return response;
}
Я делаю запрос с этим телом (игнорируйте проблему с кодировкой, источник которой находится где-то в другом месте):
[{"hash":"150a17e99f67ce29fcc600c92eee831d","instanceid":"cb440a6f-44ef-4f05-ab41-143153655b6e","text":"{"C_FirstAndLastName":"und","ContactID":"1374231","C_Fax":""}","queueDate":"2016-10-04T03:18:37"},{"hash":"1a94d9b5acff1a27dfe45be4ca5d9138","instanceid":"fdsfdsf-44ef-4f05-ab41-143153655b6e","text":"{"C_FirstAndLastName":"J?â??rgen","ContactID":"323093","C_Fax":"fsdfsd-B401-4AD3-AEA1-fdsfsdfsd"}","queueDate":"2016-10-04T03:18:37"},{"hash":"8e592fb16d464bfd0f90f69818944198","instanceid":"fdsfsdf-44ef-4f05-ab41-143153655b6e","text":"{"C_FirstAndLastName":"Claus","ContactID":"2495844","C_Fax":"fdsfsdgsd-304D-4E91-8586-fsdfsdfsd"}","queueDate":"2016-10-04T03:18:37"},{"hash":"d6d226255e62690e50abbfa15c4b5462","instanceid":"cb440a6f-44ef-4f05-ab41-143153655b6e","text":"{"C_FirstAndLastName":"Test J??rgen","ContactID":"323093","C_Fax":"fdsfsdfsd-B401-4AD3-AEA1-fdsfsdfsdf"}","queueDate":"2016-10-04T03:18:49"}]
Ответ №1:
Все, что мне нужно было сделать, это определить кодировку в выходном потоке. Не уверен, что кто-нибудь может мне в этом помочь, поскольку я только что перепробовал много вещей, и некоторые из них сработали, но, к сожалению, ничто не указывало мне в этом направлении.
os.write(body.getBytes("UTF-8"));