2017-04-15 49 views
0

以下代碼在我的PC上運行良好,服務器返回200 Ok以及正確的輸出。當我嘗試在Android上,服務器retruns:HttpURLConnections適用於PC,但不適用於Android

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 
<title>Error 405 Method Not Allowed</title> 
</head> 
<body><h2>HTTP ERROR 405</h2> 
<p>Problem accessing /sg-1/locations/. Reason: 
<pre> Method Not Allowed</pre></p><hr><i><small>Powered by Jetty://</small></i><hr/></html> 

代碼:

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); 
    connection.setDoOutput(true); // Triggers POST. 
    // connection.setRequestProperty("Accept-Charset", charset); 
    connection.setRequestProperty("Content-Type", "application/json"); 
    connection.setRequestProperty("X-Session", token); 

    connection.connect(); 
    InputStream response; 
    boolean worked = false; 
    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) 
     response = connection.getErrorStream(); 
    else { 
     response = connection.getInputStream(); 
     worked = true; 
    } 
    java.util.Scanner s = new java.util.Scanner(response).useDelimiter("\\A"); 
    String result = s.hasNext() ? s.next() : ""; 
    System.out.println(result); 

回答

0

您的代碼將在Java SE GETPOST在Android中。看來,服務器期待一個GET請求,因此防止通過刪除這一行的Android發送POST

// connection.setDoOutput(true); 
+0

似乎並非是解決方案,我刪除從我的代碼行,症狀仍然準確一樣。 – Grunzwanzling

+0

@Grunzwanzling你有控制服務器嗎?知道服務器期望的HTTP方法並明確地設置它是很重要的,例如, 'connection.setRequestMethod( 「GET」);'。我推測它是'GET' – nandsito

+0

不是,它是一個公共(非官方)API,所以我甚至不能問開發者。反正明天我會試試你的解決方案。 – Grunzwanzling

相關問題