我正在使用处理在服务器上执行简单的POST请求。我尝试了许多接受标头配置,我不断得到错误 - 406不可接受。但是,当我用postman(chrome插件)做请求时,我没有错误。
我的代码出错了,我从Java - sending HTTP parameters via POST method easily
不负责任地调整了这个代码URL url;
try {
url = new URL( urlString.toString() );
}
catch(MalformedURLException e) {
e.printStackTrace();
url = null;
}
Map <String, String> params = new HashMap<String, String>();
params.put("email", email );
params.put("mac", macAddress );
StringBuilder postData = new StringBuilder();
for ( String s : params.keySet() ) {
if (postData.length() != 0) postData.append('&');
postData.append(encode( s ));
postData.append('=');
postData.append( encode( params.get(s) ) );
}
byte[] postDataBytes;
try {
postDataBytes = postData.toString().getBytes("UTF-8");
}
catch(UnsupportedEncodingException e) {
e.printStackTrace();
postDataBytes = null;
}
HttpURLConnection conn;
try {
conn = (HttpURLConnection)url.openConnection();
}
catch(IOException e) {
e.printStackTrace();
conn = null;
}
try {
conn.setRequestMethod("POST");
}
catch(ProtocolException e) {
e.printStackTrace();
}
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
//conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Accept-Language", "es-ES,es;q=0.8,en;q=0.6");
conn.setRequestProperty("Accept", "*/*");
conn.setDoOutput(true);
try {
conn.getOutputStream().write(postDataBytes);
}
catch(IOException e) {
e.printStackTrace();
}
InputStreamReader isr;
try {
isr = new InputStreamReader( conn.getInputStream() );
}
catch(IOException e) {
e.printStackTrace();
isr = null;
}
BufferedReader in = new BufferedReader( isr );
try {
licencia = in.readLine();
}
catch(IOException e) {
e.printStackTrace();
}
当我通过邮递员(chrome插件)执行请求时,一切都很好。我使用http://requestb.in/监控了请求:
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: es-ES,es;q=0.8,en;q=0.6
Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm
Content-Length: 40
Content-Type: application/x-www-form-urlencoded
Host: requestb.in
Cookie: session=eyJyZWNlbnQiOlsid3N0MnVkd3MiXX0.BmRxhg.8OCooRI-dXug4izYc_-96Gqxa54
Cache-Control: no-cache
X-Request-Id: 9cad2bbe-84d1-496c-8d3d-26e4f2b8455f
Connection: close
原始身体:
email=sergio%40urlEncoded&mac=123POSTMAN
所以我尽力使用类似的accept-headers:
User-Agent: Java/1.6.0_33
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: es-ES,es;q=0.8,en;q=0.6
Content-Length: 27
Content-Type: application/x-www-form-urlencoded
Host: requestb.in
X-Request-Id: aa9a9739-3fc9-4cc7-a946-afaad04d178c
Connection: close
原始身体:
email=%40.&mac=C8BCC8DF14A8
但我仍然得到406错误。 ¿可能是什么问题? ¿这是服务器端的事情吗?
塞尔吉奥