我有一个非常简单的代码无效。
班级HttoCon:
package test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
public class HttpCon {
public static void main(String[] args) {
try {
sendGet();
} catch (Exception e) {
e.printStackTrace();
}
}
// HTTP GET request
private static void sendGet() throws Exception {
String url = "http://myweb.com/public/resource/data/stream";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("begin", "1430295300000");
con.setRequestProperty("end", "1430297279988");
con.setRequestProperty("id", "140621");
con.setRequestProperty("time", "FIFTEEN_MINUTE");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
}
错误追踪:
{"fault":{"exceptionType":"MissingServletRequestParameterException","host":"12.205.101.123","cause":"Required Long parameter 'id' is not present","status":"400","query":"/public/resource/data/stream","stackTrace":"org.springframework.web.bind.MissingServletRequestParameterException: Required Long parameter 'id' is not present\n\tat org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.raiseMissingParameterException(AnnotationMethodHandlerAdapter.java:774)\n\tat org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestParam(HandlerMethodInvoker.java:509)\n\tat
注意:
如果我直接在浏览器中点击了网址,那就可以了。
更新
使用curl:
curl -X GET http://myweb.com/public/resource/data/stream?begin=1430295300000&end=1430297279988&id=140621&time=FIFTEEN_MINUTE
以上卷曲不起作用且异常相同 -
curl -X GET 'http://myweb.com/public/resource/data/stream?begin=1430295300000&end=1430297279988&id=140621&time=FIFTEEN_MINUTE'
这种卷曲效果很好。
答案 0 :(得分:5)
您创建一个包含参数的String,然后将其附加到URL上。从中创建一个URL Obj。例如: -
String this.url = "http://myweb.com/public/resource/data/stream";
this.url += "?begin=1430295300000&end=1430297279988&id=140621
&time=FIFTEEN_MINUTE";
this.urlObj = new URL(this.url);
然后按照原始示例创建连接。
答案 1 :(得分:2)
openConnection
将建立连接并发出GET
。由于URL已经打开,因此忽略返回的URLConnection对象上的GET
参数的后续设置。
将参数作为查询字符串参数添加到URL,就像上面的链接一样,并打开该链接
或强>
尝试将参数发布到服务器(这更好)