我需要通过发帖请求验证用户。我使用REST协议发布我的xml数据但得到403错误。请帮我看看我做错了什么,下面是我要发布的代码。
public void makePostConnection(String fileUrl,
HashMap<String, String> requestData) {
URL url;
HttpURLConnection urlConnection;
try {
url = new URL(fileUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(fileUrl);
httppost.addHeader("accept", "text/xml");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
requestData.size());
System.out.println("Size= " + requestData.size());
for (Entry<String, String> entry : requestData.entrySet()) {
nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry
.getValue()));
System.out.println("Key= " + entry.getKey() + " Value= "
+ entry.getValue());
}
System.out.println("Request ba= " + nameValuePairs.toString());
StringEntity requestBody = new StringEntity(
nameValuePairs.toString());
// requestBody.setContentType("text/xml");
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setEntity(requestBody);
// httppost.set
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
int code = response.getStatusLine().getStatusCode();
System.out.println("Code= " + code);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
答案 0 :(得分:1)
嗨,我通过改变我设置的一行解决了我的问题 httppost.addHeader( “内容类型”, “应用程序/ x WWW的形式进行了urlencoded”); 并通过这样做一个urlencoded请求 UrlEncodedFormEntity ent = new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8); 以下是我提出成功请求的所有代码。
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(fileUrl);
httppost.addHeader("Content-Type",
"application/x-www-form-urlencoded");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
requestData.size());
System.out.println("Size= " + requestData.size());
for (Entry<String, String> entry : requestData.entrySet()) {
nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry
.getValue()));
System.out.println("Key= " + entry.getKey() + " Value= "
+ entry.getValue());
}
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(nameValuePairs,
HTTP.UTF_8);
httppost.setEntity(ent);
HttpResponse response = httpclient.execute(httppost);
int code = response.getStatusLine().getStatusCode();
System.out.println("Code= " + code);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}