我在这个java函数中遇到问题我试图将数据从我的表发布到服务器但是因为我已经连接错误而无法发布错误
仅发布第一条记录
public int myfuction(){
try{
String url = "myurl/page.php";
String urlParameters=null;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
Cursor c1 = db.rawQuery("SELECT * FROM temtable ", null);
String id = null;
if (c1 != null ) {
if (c1.moveToFirst()) {
do {
suid = c1.getString(c1.getColumnIndex("puid"));
urlParameters ="text=STAT=1,DEVICEID=10,TERMINALID="+terminal+",USERID="+id;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//con.disconnect();
Toast.makeText(this, "Send Para-"+urlParameters, Toast.LENGTH_SHORT).show();
pstatus = 1;
}while (c1.moveToNext());
}
}
con.disconnect();
Toast.makeText(this, "Send Success", Toast.LENGTH_SHORT).show();
}
catch(Exception ex)
{
Toast.makeText(this, "Error:"+ ex.getMessage(), Toast.LENGTH_SHORT).show();
}
return 1;
}
这就是我正在使用的请帮助...
答案 0 :(得分:2)
每次都需要在循环内通过HttpURLConnection
创建新的URL.openConnection()
。您尝试进行连接池,但HttpURLConnection
已经为您做了。完成上一次迭代后,请调用disconnect()
以提供可以关闭此连接的提示。
答案 1 :(得分:-1)
我在while循环中尝试过这个片段本身对我有用并且每次都断开连接
但是连接和断开它为服务器加载了这么多请求的每个请求都是不好的做法
String url = "myurl/page.php";
String urlParameters=null;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
那么还有其他解决方案,只有一次我可以连接并在该连接上逐个发布数据