我确实确实需要一些帮助,以便使用especific标头和主体发出多线程POST请求,该标头和主体应在终端中返回JSON。
评论信息:
Java中不同线程中的多个POST请求
答案 0 :(得分:0)
这里有一篇快速的文章,可以让您有所作为。它使用POST Web服务并通过可运行线程打印响应。您绝对必须对它进行结构设计,以适合您的代码框架。
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.io.IOUtils;
public class MultiThreadedRestConsumer {
public static void main(String[] args) {
Thread t1 = new Thread(new POSTRestConsumer({URI Here}, {JSON String Body}, {Map of String, Value For Header attributes});
t1.start();
//TODO you can create as many threads to consume REST
}
}
class POSTRestConsumer implements Runnable {
private String body;
private String uri;
private Map<String, String> header;
public POSTRestConsumer(String uri, String body, Map<String, String> header) {
this.uri = uri;
this.body = body;
this.header = header;
}
@Override
public void run() {
HttpURLConnection connection = null;
try {
// open connection
connection = (HttpURLConnection) new URL(uri).openConnection();
// set header
for (Entry<String, String> entry : header.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
// ensure to set required header if not supplied already
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json");
// set body
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
os.write(body.getBytes("UTF-8"));
os.flush();
os.close();
// read response
StringWriter writer = new StringWriter();
IOUtils.copy(connection.getInputStream(), writer, "UTF-8");
System.out.println(writer.toString());
writer.flush();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// ensure connection is released
if (connection != null) {
connection.disconnect();
}
}
}
}