[英]Java - writing to url not working
我正在尝试制作一个Java程序来更改我网站上的文本文档。 权限是所有人都可以编辑的。 我已经尝试过,并且阅读效果很好,但是写作却没有。 这是编写代码:
import java.net.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
URL infoThing = new URL("http://www.[name of my website]/infoThing.txt");
URLConnection con = infoThing.openConnection();
con.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.write("Change to this.");
out.close();
}
}
为了使Java程序与服务器端进程进行交互,它仅必须能够写入URL,从而向服务器提供数据。 通过执行以下步骤可以做到这一点:
1创建一个URL。
2检索URLConnection对象。
3在URLConnection上设置输出功能。
4打开与资源的连接。
5从连接获取输出流。
6写入输出流。
7关闭输出流。
如果要写入URL。 您必须使用以上概念和servlet的概念。 通过URLConnection在网络上运行向后脚本的示例程序:
import java.io.*;
import java.net.*;
public class ReverseTest {
public static void main(String[] args) {
try {
if (args.length != 1) {
System.err.println("Usage: java ReverseTest string_to_reverse");
System.exit(1);
}
String stringToReverse = URLEncoder.encode(args[0]);
URL url = new URL("http://java.sun.com/cgi-bin/backwards");
URLConnection connection = url.openConnection();
PrintStream outStream = new PrintStream(connection.getOutputStream());
outStream.println("string=" + stringToReverse);
outStream.close();
DataInputStream inStream = new DataInputStream(connection.getInputStream());
String inputLine;
while ((inputLine = inStream.readLine()) != null) {
System.out.println(inputLine);
}
inStream.close();
} catch (MalformedURLException me) {
System.err.println("MalformedURLException: " + me);
} catch (IOException ioe) {
System.err.println("IOException: " + ioe);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.