我必須向web服務發送請求以使用用戶名和密碼對用戶進行身份驗證。JAVA:http發佈請求
我有以下POST請求的一個問題:
public String postTest(String action, ConnectionParametrData [] parameters) {
Uri.Builder builder = new Uri.Builder().scheme(scheme).authority(authority).path(action);
uri = builder.build();
BufferedReader in = null;
String ans = null;
HttpPost request = new HttpPost(uri.toString());
HttpClient defaultClient = new DefaultHttpClient();
try {
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
request.setEntity(new UrlEncodedFormEntity(getValuePairs(parameters)));
HttpResponse response = defaultClient.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"), 8192);
StringBuffer sb = new StringBuffer("");
String line = "";
String newLine = System.getProperty("line.separator");
while((line = in.readLine()) != null) {
sb.append(line + newLine);
}
ans = sb.toString();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ans;
}
當我執行該方法服務器拋出錯誤告訴請求不是POST請求。
但這種方法的工作完美:
private String makePost(String action, ConnectionParametrData [] parameters) throws IOException {
StringBuilder urlBuild = new StringBuilder();
urlBuild.append(scheme).append("://www.").append(authority).append(action);
URL url = new URL(urlBuild.toString());
URLConnection urlConnection = url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream printout = new DataOutputStream(urlConnection.getOutputStream());
String content = getParameters(parameters);
printout.writeBytes(content);
printout.flush();
printout.close();
BufferedReader in = null;
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()), 8192);
StringBuffer sb = new StringBuffer("");
String line = "";
String newLine = System.getProperty("line.separator");
while((line = in.readLine()) != null) {
sb.append(line + newLine);
}
in.close();
return sb.toString();
}
我更喜歡使用的HttpClient比URLConecction, 沒有任何人知道爲什麼第一個方法沒有被批准爲POST?
「拋出錯誤」 - 以異常的形式?你有沒有檢查過線上的實際情況(WireShark)? – Fildor
@wilek 你可以打印URI.toString()併發布它嗎? –