简体   繁体   English

Java-写入url不起作用

[英]Java - writing to url not working

I'm trying to make a java program that changes a text document on my website. 我正在尝试制作一个Java程序来更改我网站上的文本文档。 The permissions are on that everyone can edit it. 权限是所有人都可以编辑的。 I've tried, and reading it works perfectly, but writing doesn't. 我已经尝试过,并且阅读效果很好,但是写作却没有。 Here's the code for the writing: 这是编写代码:

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();
    }
}

For a Java program to interact with a server-side process it simply must be able to write to a URL, thus providing data to the server. 为了使Java程序与服务器端进程进行交互,它仅必须能够写入URL,从而向服务器提供数据。 It can do this by following these steps: 通过执行以下步骤可以做到这一点:

1 Create a URL. 1创建一个URL。

2 Retrieve the URLConnection object. 2检索URLConnection对象。

3 Set output capability on the URLConnection. 3在URLConnection上设置输出功能。

4 Open a connection to the resource. 4打开与资源的连接。

5 Get an output stream from the connection. 5从连接获取输出流。

6 Write to the output stream. 6写入输出流。

7 Close the output stream. 7关闭输出流。

If you want to write to the url. 如果要写入URL。 You have to use the concepts above and concepts for servlets. 您必须使用以上概念和servlet的概念。 An example program that runs the backwards script over the network through a URLConnection: 通过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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM