使用HttpURLConnection与远程服务器的java连接
我尝试使用HttpURLConnection
将json对象发送到远程服务器。
但是这个错误被显示出来了
"Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 401
at TestSendSMS.main(TestSendSMS.java:40)"
我不知道出了什么问题。这段代码怎么了?需要帮忙吗
try {
/*
* JSONObject jsonParam = new JSONObject();
* jsonParam.put("-----","----"); jsonParam.put("----","-----");
* jsonParam.put("-----","-----");
*/
String input = "{\"------\":\"------\",\"-----\":\"------\",\"------\":\"-----\"}";
System.out.println("JsonObj " + jsonParam);
URL myURL = new URL("-----------------------");
HttpURLConnection myURLConnection = (HttpURLConnection) myURL
.openConnection();
myURLConnection.setDoOutput(true);
myURLConnection.setDoInput(true);
myURLConnection.setChunkedStreamingMode(0);
myURLConnection.setUseCaches(false);
myURLConnection.setConnectTimeout(10000);
myURLConnection.setReadTimeout(10000);
myURLConnection.setRequestProperty("Content-Type",
"application/json");
myURLConnection.setRequestProperty("Accept", "application/json");
OutputStream os = myURLConnection.getOutputStream();
os.write(input.getBytes());
os.flush();
if (myURLConnection.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ myURLConnection.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(myURLConnection.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
myURLConnection.disconnect();
} catch (MalformedURLException e) {
System.out.println("error1");
}
catch (IOException e) {
System.out.println("error2");
}
# 1 楼答案
HTTP Error 401
是一个身份验证问题发送请求时需要向服务器进行身份验证
本主题可能会帮助您通过URLConnection进行身份验证:
How to handle HTTP authentication using HttpURLConnection?