我没有错误,但我的代码没有将任何新数据保存到文本文件中,这是我的代码:
public void saveToLeaderboard() throws IOException {
String toSave = "Random info I want to save";
HttpConnection connection = null;
connection = (HttpConnection) Connector.open("EXTERNAL URL", Connector.READ_WRITE, true);
connection.setRequestMethod(HttpConnection.POST);
DataOutputStream out = new DataOutputStream(connection.openDataOutputStream());
out.writeUTF(toSave);
out.flush();
connection.close();
}
我做错了什么?
答案 0 :(得分:0)
我在代码中看不到任何FileOutputStream。 DataOutputStream应该如何编写文件?
答案 1 :(得分:0)
要实际触发HTTP请求,您需要获取有关HTTP响应的任何信息,例如使用URLConnection.getInputStream()
或URLConnection.getResposeCode()
的响应正文等。
有关详细信息,请参阅How HTTP request works。
答案 2 :(得分:0)
我在一天结束时的解决方案:
我创建了一个服务器端文件(在我的例子中是一个.Net文件[.aspx]),我设置了我的外部URL以调用我的.Net页面,其中包含保存所需数据的url变量。
并使用服务器代码(在我的情况下为C#)对txt文件进行了基本保存。
public void saveToLeaderboard() throws IOException {
String toSave = "Data to save";
InputStream inputStream = null;
HttpConnection connection = (HttpConnection) Connector.open("External Url" + "?info=" + toSave, Connector.READ_WRITE, true);
connection.setRequestMethod(HttpConnection.POST);
inputStream = connection.openInputStream();
inputStream.close();
connection.close();
}
答案 3 :(得分:0)
最好尝试以下编码代码
public void saveToLeaderboard() {
String toSave = "Random info I want to save";
HttpConnection connection = null;
int response_code=HttpConnection.HTTP_OK-1;
FileConnection fc=null;
DataOutputStream dos=null;
DataOutputStream out
InputStream dis=null;
try
{
connection = (HttpConnection) Connector.open("EXTERNAL URL");
connection.setRequestMethod(HttpConnection.POST);
out= connection.openDataOutputStream();
out.writeUTF(toSave);
out.flush();
response_code=connection.getResponseCode();
if(response_code==HttpConnection.HTTP_OK)
{
dis=connection.openDataInputStream();
int ch;
fc=(FileConnection)Connector.open(path,Connector.READ_WRITE); //path is a path of the file to be saved
fos=fc.openDataOutputStream(); byte temp; while((ch=dis.read()) !=-1)
{
temp=(byte)ch; fos.write(temp);
}
fos.flush();
}
else
{ //Status code not ok }
}
catch(ConnectionNotFoundException cnex){//Connection not found}
catch(IOException cnex){//ioe exception}
catch(Exception cnex){//exception}
if(out!=null)
{
try{
out.close();
}
catch(Exception cnex){//exception}
}
if(dis!=null)
{
try{
dis.close();
}
catch(Exception cnex){//exception}
}
if(connection!=null)
{
try{
connection.close();
}
catch(Exception cnex){//exception}
}
if(fos!=null)
{
try{
fos.close();
}
catch(Exception cnex){//exception}
}