Android HttpURLConnection发布请求fileNotFound

时间:2016-06-21 19:59:26

标签: android httpurlconnection

我必须向<!DOCTYPE html> <html> <body> <img id="myImage" src="Light1.gif" width="500" height ="350"> <p><button onclick="myFunction()">Change Light</button><p> <p> Click Change Light to change the traffic light. </p> </body> </html>提出POST请求,该请求期待以下内容:

ASP WEB APi 2 with OWIN login

但是,我总是通过grant_type=password password=qwerty username=administrator responseCode获得FileNotFound异常。我不确定我是否以正确的方式发送400数据。这是我的代码:

POST

修改

以下是public JSONObject getLoginToken(String username, String password) { URL url = null; HttpURLConnection httpURLConnection = null; BufferedReader bufferedReader = null; JSONObject response = null; try { url = new URL("someUrl"); httpURLConnection = (HttpURLConnection) url.openConnection(); JSONObject data = new JSONObject(); data.put("username", username); data.put("password", password); data.put("grant_type", "password"); httpURLConnection.setChunkedStreamingMode(0); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); OutputStream os = httpURLConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(URLEncoder.encode(data.toString(), "UTF-8")); writer.flush(); writer.close(); os.close(); httpURLConnection.connect(); bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); // <-- fails here StringBuilder sb = new StringBuilder(); String line = null; while ((line = bufferedReader.readLine()) != null) { sb.append(line + "\n"); } response = new JSONObject(sb.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); } } return response; } 中端点的创建方式,如果有任何帮助的话。

C#

1 个答案:

答案 0 :(得分:0)

不,这不是正确的方法。 HERE你可以找到两个有用的答案如何正确地做到这一点(我推荐第二个,没有标记)