我从GWT-Client提交JSON数据并将其传递给我的GWT-Server。我想将数据重新提交到另一台服务器,并希望从另一台服务器响应GWT-Client。
我只是不知道我该怎么做。我尝试了以下代码,但没有工作。
我的代码是:
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("POST");
StringBuffer jb = new StringBuffer();
URL oracle = new URL("http://www.google.com");
HttpURLConnection connection = null;
connection = (HttpURLConnection) oracle.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
request.getInputStream();
OutputStream wr = connection.getOutputStream();
InputStream in = request.getInputStream();
byte[] buffer = new byte[512];
int read = in.read(buffer, 0, buffer.length);
while (read >= 0) {
wr.write(buffer, 0, read);
read = in.read(buffer, 0, buffer.length);
}
wr.flush();
wr.close();
BufferedReader in1 = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in1.readLine()) != null) {
jb.append(inputLine);
}
response.setContentType("text/html");
// Get the printwriter object from response to write the required json
// object to the output stream
PrintWriter out = response.getWriter();
// Assuming your json object is **jsonObject**, perform the following,
// it will return your json object
out.print(jb.toString());
out.flush();
in1.close();
}
请帮帮我。
答案 0 :(得分:1)
在阅读回复
之前,您必须将请求发送到其他服务器URL oracle = new URL("http://www.anotherserver.com/");
HttpURLConnection connection = null;
connection = (HttpURLConnection) oracle.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStream wr = connection.getOutputStream ();
InputStream in = request.getInputStream();
byte[] buffer = new byte[512];
int read = in.read(buffer,0, buffer.length);
while (read >= 0) {
wr.write(buffer,0, read);
read = in.read(buffer,0,buffer.length);
}
wr.flush ();
wr.close ();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
jb.append(inputLine);
}
另见Using java.net.URLConnection to fire and handle HTTP requests
答案 1 :(得分:1)
此外,您可以使用Apache httpclient,实现您的要求非常简单,例如:
public static void main(String[] args) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.anotherserver.com/");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("key",
"value"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}