2017-12-07 4 views
0

HttpUrlConnectionを使用してAndroidからASP.net Web APIにPOSTリクエストを送信したとき。それは動作していないようです。上記のコードを実行するとき、それはAndroidからPOSTリクエストをJavaでASP.net Web APIに送信

conn.getInputStream() 

内にFileNotFoundExceptionを有するであろう

String baseUrl = "http://<IP Address>/Save/Document"; 
URL url = new URL(baseUrl); 
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 

conn.setRequestMethod("POST"); 
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); 
DataOutputStream os = new DataOutputStream(conn.getOutputStream()); 

JSONObject ap = new JSONObject(); 
// Where data is a JSON string 
// Like [{Test: 1}, {Test: 2}] 
ap.put("",new Gson().toJson(data)); 

OutputStreamWriter ap_osw= new OutputStreamWriter(conn.getOutputStream()); 
ap_osw.write(ap.toString()); 
ap_osw.flush(); 
ap_osw.close(); 

BufferedReader br = new BufferedReader(new InputStreamReader(
        (conn.getInputStream()))); 

StringBuilder response = new StringBuilder(); 
while ((output = br.readLine()) != null) { 
    response.append(output); 
    response.append('\r'); 
} 
String mes = response.toString(); 
Log.i("INFO", mes); 
conn.disconnect(); 

IものHttpClientスタイルのソースコードを実装しようとしました。

HttpClient httpClient = new DefaultHttpClient(); 
HttpPost httpPost = new HttpPost(baseUrl); 

try { 
    StringEntity se = new StringEntity((new Gson()).toJson(data)); 
    httpPost.setEntity(se); 
    httpPost.setHeader("Accept", "application/json"); 
    httpPost.setHeader("Content-Type", "application/json"); 

    HttpResponse response = httpClient.execute(httpPost); 
    InputStream inputStream = response.getEntity().getContent(); 

    String result = ""; 
    if (inputStream != null) 
      result = convertInputStreamToString(inputStream); 
    else 
      result = "Did not work!"; 

    Log.i("RESPONSE", result); 

} catch (Exception ex) { 
    Log.i("Exception", ex.getMessage()); 
} 
return output; 

今回は「要求されたリソースがhttpメソッド 'get'をサポートしていません」と表示されます。

AndroidからASP.net Web APIにデータを送信するPOSTリクエストメソッドを実装する方法はありません。どんな勧告?

最後に、次のコーディングは参考のために私のASP.net Web APIです。

[HttpPost] 
[Route("Save/Document")] 
public HttpResponseMessage Post([FromBody]string model) 
{ 
    var resp = new HttpResponseMessage(HttpStatusCode.OK); 
    resp.Content = new StringContent(model, System.Text.Encoding.UTF8, "text/plain"); 
    return resp; 
} 
+0

郵便配達員のように手動でAPIをテストしましたか? –

+0

あなたのアプリで使用する前に –

+1

Retrofit Apiを使用すると、リクエストが非常に簡単で効率的です。 –

答えて

0

最後に、この問題を解決する解決策がありました。これは、要求本体のPOSTデータがWeb APIから読み取られないためです。

要求のContent-Typeが「アプリケーション/ JSON」であり、文字列を使用して

、リクエストボディは、プレーンテキスト(例えば、「テキストメッセージ」)であるべきです。自己定義されたクラスを使用

[FromBody] string inStr 

は、リクエストボディは、JSON文字列でなければならない (例えば{KEY:VALUE})

自己定義されたクラスの配列を使用
[FromBody] YourClass inObj 

、リクエストボディがなければなりませんJSON配列文字列(例えば、[{KEY:VALUE}])

[FromBody] YourClass[] inObj 

自己定義されたクラスは、以下のようにのようにすべきである: -

class YourClass { 
    public string KEY { get; set; } 
} 

Btw。すべての返信や有用な情報をありがとう。

+0

あなたは完全なコードをAndroidとC#で表示できますか? – zxc

関連する問題