我正在尝试向Https webservice
发送请求,但它始终返回404 Not Found
(此服务器上找不到请求网址),但它在浏览器中完美运行。它返回以XML
格式回复。请帮帮我们。
这是我的代码
try {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));
HttpParams param = new BasicHttpParams();
SingleClientConnManager mgr = new SingleClientConnManager(param,
schemeRegistry);
HttpClient client = new DefaultHttpClient(mgr, param);
HttpPost post = new HttpPost(Global.CARD_API_URL);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("user", "xxx"));
parameters.add(new BasicNameValuePair("pass", "xxxxxxxx"));
parameters.add(new BasicNameValuePair("cardNumber",
"xxxxxxxxxxxxxxxx"));
parameters.add(new BasicNameValuePair("expiryDate", "0515"));
parameters.add(new BasicNameValuePair("cvc", "123"));
post.setEntity(new UrlEncodedFormEntity(parameters));
HttpResponse response = client.execute(post);
String res = EntityUtils.toString(response.getEntity());
Log.d("Card Details", res);
} catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:0)
试试这段代码,它可以帮助你......
SSLContext ctx;
try {
ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[] {
new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) {}
public void checkServerTrusted(X509Certificate[] chain, String authType) {}
public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; }
}
}, null);
HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
答案 1 :(得分:0)
最后我解决了这个问题。我需要使用Simple HTTP Url Connection而不是上面的方法。
这是代码
try {
url = new URL(api_url);
URLConnection connection = url.openConnection();
HttpURLConnection http_connection = (HttpURLConnection) connection;
http_connection.setConnectTimeout(10000);
// Set the appropriate HTTP parameters.
http_connection.setRequestMethod("POST");
http_connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded; charset=utf-8");
http_connection.setDoOutput(true);
http_connection
.setFixedLengthStreamingMode(post_data.getBytes().length);
DataOutputStream dos = new DataOutputStream(
http_connection.getOutputStream());
dos.writeBytes(post_data);
dos.flush();
dos.close();
// Read the response.
InputStreamReader isr = new InputStreamReader(
http_connection.getInputStream());
BufferedReader in = new BufferedReader(isr);
sb = new StringBuffer();
// Write the message response to a String.
while ((response = in.readLine()) != null) {
sb.append(response);
}
Log.d("Card Details", sb.toString());
}catch(Exception e){
e.printStackTrace();
}