您好我正在尝试使用 HttpURLConnection POST 方法执行服务器请求,但没有收到任何回复,我在SO中看到了一些帖子,但我无法理解它们。以下是我的代码
@Override
protected String doInBackground(Void... arg0) {
try{
System.out.println("inside try clockr=====");
String urlParameters = "Username=sadmin&Password=s4dm1ncoe";
String request = "http://10.xx.xx.xxx/eai_enu/start.swe?SWEExtSource=WebService&SWEExtCmd=Execute&Username=sadmin&Password=s4dm1ncoe";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.connect();
System.out.println("checking response=====");
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println("checking response====="+response.toString());
return response.toString();
//connection.disconnect();
}catch(Exception e){
System.out.println("checking error====="+e.toString());
return new String("Exception: " + e.getMessage());
}
}
}
上面的代码给出了错误 FilenotfoundExcepttion stacktrace,如下所示
07-15 12:35:47.656: I/System.out(30352): checking error=====java.io.FileNotFoundException: http://10.xx.xx.xxx/eai_enu/start.swe?SWEExtSource=WebService&SWEExtCmd=Execute&Username=sadmin&Password=s4dm1ncoe
这是我的网址http://10.xx.xx.xxx/eai_enu/start.swe?SWEExtSource=WebService&SWEExtCmd=Execute&Username=sadmin&Password=s4dm1ncoe"
有人可以帮忙解释如何为我的网址设置参数吗?
答案 0 :(得分:0)
您应该设置 setConnectTimeout()
& setReadTimeout()
并在catch()
例外区块中执行超时工作。
try {
String path = "http://www.your.web.path/";
HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
if(conn.getResponseCode() == 200){
//...
}
} catch (Exception e) {
e.printStackTrace();
//do your timeout work here.
}
如果忽略setReadTimeout()
,可能会出现一些问题,请参阅Here。