2016-06-21 64 views
1

我必须做出一个POST请求到ASP WEB APi 2 with OWIN login这是期待了以下机身:的Android HttpURLConnection的POST请求fileNotFound

grant_type=password 
password=qwerty 
username=administrator 

不过,我总是得到FileNotFound异常与400 responseCode。我不确定我是否以正确的方式发送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#创建的,如果它的任何帮助。

var client = new RestClient(Statics.API_LOCATION_URL + "login"); 
var request = new RestRequest(Method.POST); 
request.AddParameter("grant_type", "password"); 
request.AddParameter("username", "administrator"); 
request.AddParameter("password", "qwerty"); 

回答

0

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

+0

试图已经像这样'String data = URLEncoder.encode(“username =”+ username +“&password =” +密码+“&grant_type =密码”,“UTF-8”);'。仍然有相同的错误 – XeniaSis

+0

没有更多我没有看到...我会尝试寻找在服务器端的答案...还写了“......期待以下**身体** ...” - 你确定你必须在POST方法中发送参数?你也使用'setChunkedStreamingMode(0)'和doc:“...注意,**不是所有的** HTTP服务器都支持这种模式。”另外:设置一些超时;)我只能说,祝你好运! – snachmsm

+0

你可以查看编辑吗?也许它有帮助。 – XeniaSis

相关问题