行。我的问题是,当我尝试通过 Java 中的终端向服务器发送 HTTP PUT 请求到服务器“ http://scratch.mit.edu/ ”时,我得到的回复是该命令不存在。所以我直接从终端尝试了。仍然没有工作。有没有什么方法可以让我不必安装 curl 之类的程序,这样我就可以做到这一点?我将与其他几个人共享这个程序,所以我不想让他们安装程序。通过终端,我可以这样做吗?或者,是否有一个WORKING java 命令?我见过很多人没有测试它,它不起作用!请帮我!!!!丁:
这是我的程序(程序没有问题,只有找到正确的终端命令!D :)
package com.mkyong.shell;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExecuteShellComand {
public static void main(String[] args) {
ExecuteShellComand obj = new ExecuteShellComand();
int studio = 497688;
String command = "PUT /site-api/users/curators-in/" +studio +"/remove/?usernames=arinerron HTTP/1.1 \nHost: scratch.mit.edu \nAccept: */* \nAccept-Encoding: gzip,deflate,sdch \nAccept-Language: en-US,en;q=0.8 \nCookie: __qca=P0-1926269269-1400108554400; scratchcsrftoken=cQBcHRVvjG3LsQROJdCq1Ljmdi4bWnjB; scratchsessionsid=c36fe777199a51f3556f4ab97c62cc0a; __utma=133675020.292999539.1399158737.1406949614.1406996049.322; __utmb=133675020.85.9.1407000438801; __utmc=133675020; __utmz=133675020.1406740512.306.14.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided) \nDNT: 1 \nOrigin: http://scratch.mit.edu \nReferer: http://scratch.mit.edu/studios/" +studio +"/curators/ \nUser-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/34.0.1847.116 Chrome/34.0.1847.116 Safari/537.36 \nX-CSRFToken: cQBcHRVvjG3LsQROJdCq1Ljmdi4bWnjB \nX-Requested-With: XMLHttpRequest \nHTTP/1.1 200 OK \nAccept-Ranges: bytes \nAccess-Control-Allow-Credentials: true \nAccess-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control \nAccess-Control-Allow-Methods: OPTIONS, GET, POST \nAccess-Control-Allow-Origin: * \nAge: 0 \nConnection: keep-alive \nContent-Encoding: gzip \nContent-Language: en \nContent-Length: 287 \nContent-Type: text/html; charset=utf-8 \nDate: Sat, 02 Aug 2014 17:33:19 GMT \nServer: Scratch Web Server \nVary: Accept-Encoding, Accept-Language, Cookie \nVia: 1.1 varnish \nX-Cache: MISS \nX-Cache-Hits: 0 \nX-Varnish: 1986766295";
String output = obj.executeCommand(command);
System.out.println(output);
}
private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
2017 年 9 月编辑:哈哈,这是一个非常愚蠢的问题。这大约是我学习 Java 的时候,所以我无法修复它。那时我12岁。现在,我会为此使用 Apache httpcomponents - HttpUrlConnection 是非常糟糕的 IMO,并且通过终端从 Java 发送 http 请求是一件可怕的事情。