【发布时间】:2026-02-02 10:15:01
【问题描述】:
我正在尝试使用以下代码从HttpURLConnection 解析来自InputStream 的响应。尝试获取InputStream 时出现错误。我只是想获得响应以检查是否网络服务调用工作OK。
static final String SOAP_ACTION="http://888topup.com/ImageProcess.svc/UploadImage";
java.net.URL url=null;
try {
url = new java.net.URL(SOAP_ACTION);
} catch (MalformedURLException e) {
Log.e(TAG, "Bad URL",e);
}
JSONObject obj=new JSONObject();
try {
obj.put("Vaue", value);
} catch (JSONException e) {
Log.e(TAG, "Create JSONObjerct throws an error");
}
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection)url.openConnection();
} catch (IOException e1) {
Log.e(TAG,"Error opening connection",e1);
}
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
try {
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Accept", "*/*");
urlConnection.addRequestProperty("Accept-Encoding", "gzip deflate sdch");
urlConnection.setRequestProperty("Content-Type","application/json");
} catch (ProtocolException e) {
Log.e(TAG,"Error setting header",e);
}
try {
OutputStream os=urlConnection.getOutputStream();
BufferedOutputStream bos=new BufferedOutputStream(os);
byte[] data=obj.toString().getBytes();
bos.write(data);
InputStream is=urlConnection.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String response;
response=br.readLine();
Log.d(TAG, "Response: "+response);
bos.close();
br.close();
is.close();
urlConnection.disconnect();
} catch (IOException e) {
Log.e(TAG,"Error peforming read-write operations",e);
}
这是Logcat 条目,说明我尝试运行此代码时发生的情况:
MainActivity(9628): Error peforming read-write operations
MainActivity(9628): java.io.FileNotFoundException: http://888topup.com/ImageProcess.svc/UploadImage
MainActivity(9628): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
MainActivity(8989): at com.example.imageuploadtest.MainActivity.sendStringToServiceUsingRest(MainActivity.java:184)
MainActivity(8989): at com.example.imageuploadtest.MainActivity.access$0(MainActivity.java:149)
MainActivity(8989): at com.example.imageuploadtest.MainActivity$1$1.run(MainActivity.java:66)
编辑:
WSDL中指定的操作:
<wsdl:operation name="UploadImage">
<wsdl:input wsaw:Action="http://tempuri.org/IImageProcess/UploadImage" message="tns:IImageProcess_UploadImage_InputMessage"/>
<wsdl:output wsaw:Action="http://tempuri.org/IImageProcess/UploadImageResponse" message="tns:IImageProcess_UploadImage_OutputMessage"/>
</wsdl:operation>
在将数据写入OutputStream 之前添加urlConnection.connect() 也不起作用。
编辑:使用 URL(SOAP_ACTION) 并传递来自 Sencha-Touch 的 jsondata 作品,供其他测试过的人使用。
尝试将 JSONObject 作为字符串而不是字节数据传递。也不起作用?
【问题讨论】:
-
你忽略了实际的异常。
-
@EJP 添加了异常和 URL
-
既然你已经提供了,
not found ... http://888topup.com/ImageProcess.svc/UploadImage的哪一部分你不明白? -
我尝试将JSON数据传递给输出流到服务,是否意味着请求不成功,如何在不使用InputStream的情况下从服务获取响应
-
你没有抓住重点。无效的是 URL 本身。与代码无关。
标签: java android inputstream httpurlconnection