我一直在尝试使用我的Android应用程序将包含用户个人资料的XML数据上传到我的OneDrive帐户。
无论我在互联网上找到什么示例代码,我的应用都不会上传任何数据。理想情况下,我希望尽可能保持我的代码简单(我仍然非常缺乏经验),但如果不安装插件和插件,可能根本无法实现这一点。 OneDrive的SDK包?是否有其他文件托管服务(Google Drive,Drop Box等),这种简单的代码可以使用?提前谢谢!
我尝试使用的代码如下:
import android.os.AsyncTask;
import android.widget.TextView;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.util.Scanner;
public class UploadProfileTask extends AsyncTask<String, Void, String> {
private TextView textView;
public UploadProfileTask(TextView textView) {
this.textView = textView;
}
@Override
protected String doInBackground(String... urls) {
try {
return uploadUrl(urls[0]);
} catch (XmlPullParserException e) {
return "Xml error. URL may be invalid.";
} catch (IOException e) {
return "Connection error. URL may be invalid.";
} catch (ParseException e) {
return "Parse error. URL may be invalid.";
}
}
@Override
protected void onPostExecute(String result) {
textView.setText(result);
}
private String uploadUrl(String urlString) throws IOException, XmlPullParserException, ParseException {
try{
URL url = new URL(urlString);
// Get the user profile as an XML string.
String param = Globals.SerializeProfile;
HttpURLConnection conn =(HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(param.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.close();
String response= "";
Scanner inStream = new Scanner(conn.getInputStream());
while(inStream.hasNextLine())
response+=(inStream.nextLine());
}
catch(MalformedURLException ex){
}
catch(IOException ex){
}
return "Profile uploaded successfully";
}
}