REST POST请求不适用于java但适用于REST客户端

时间:2017-02-08 11:12:43

标签: java c# android rest post

早上好!

我已经使用C#创建了一个REST服务,并且我尝试将来自android-studio的帖子请求发送到URL。我的URL目前有两种方法,GET和POST。 GET方法工作正常,我可以毫无问题地从android中使用。但是当谈到POST请求时,我无法从android中使用它。

我使用REST客户端chrome附加组件测试了POST方法,看起来请求工作正常,我能够访问该方法并执行代码需要执行的任何内容。证据下方:

请求数据:

Request data

请求回复:

Request response

在C#api下面:

[RoutePrefix("api/leads")]
    public class LeadsController : ApiController
    {
        // GET: api/Leads/5
        public List<Lead> Get(string matricula, int tipo)
        {
            List<Lead> leads = new List<Lead>();

            //Fills the list

            return leads;
        }

        [HttpPost]
        // POST: api/Leads
        public bool Post(int id, string usuario, string latitude, string longitude)
        {
            //Do stuff

            return true;
        }
}

最后,但并非最不重要的是,我用于POST请求的java代码:

@Override
    protected String doInBackground(String... strings) {
        URL url = null;
        try {
            String newUrl = getNewUrl();

            StringBuilder postData = new StringBuilder();

            for (Map.Entry<String,Object> param : params.entrySet()) {
                if (postData.length() != 0) postData.append('&');
                postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                postData.append('=');
                postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
            }

            url = new URL(newUrl);

            byte[] postDataBytes = postData.toString().getBytes("UTF-8");

            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));


            conn.getOutputStream().write(postDataBytes);

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                server_response = readStream(conn.getInputStream());
            }

        } catch (MalformedURLException e) {
            listener.onPostResponse(false, e.getMessage(), this.tipoAcesso);
        } catch (UnsupportedEncodingException e) {
            listener.onPostResponse(false, e.getMessage(), this.tipoAcesso);
        } catch (ProtocolException e) {
            listener.onPostResponse(false, e.getMessage(), this.tipoAcesso);
        } catch (IOException e) {
            listener.onPostResponse(false, e.getMessage(), this.tipoAcesso);
        }
        return null;
    }

方法getNewUrl()返回的URL是:&#34; https://cliente.teleatlantic.com.br/CheckinLeads/api/Leads/&#34;。

参数为:&#34; usuario = FERNANDOCHAVES&amp; latitude = -46.6903502&amp; longitude = -46.6903502&amp; id = 265857&#34;

我在网上(包括这个论坛)孜孜不倦地寻找一种解决POST请求问题的方法。但是我找到的解决方案都没有解决我的问题。

到目前为止我所做的尝试:
1.Append&#34;?&#34;在POST请求中发送参数之前 2.Append&#34; / CheckinLeads / api / Leads?&#34;在参数之前。
3.更改代码以使用HttpClient而不是HttpURLConnection 4.将内容数据更改为&#34; text / json&#34;。
5.许多&#34;随时可以使用&#34;使用HttpURLConnection和HttpClient进行函数。

我是java / android的新手,任何帮助都会受到赞赏 我使用的是4.4 Android KitKat SDK版本24 感谢您的关注!最好的问候。

----- ----- EDIT
代码没有崩溃。但是,当我检查请求的HttpURLConnection.getResponseCode时,它会向我显示404.但是我发送的URL和参数与用于在REST客户端中测试的相同。

2 个答案:

答案 0 :(得分:2)

Change the api code 

public class test { 
public int id {get;set;} 
public string usuario {get;set;} 
public string latitude {get;set;} 
public string longitude { get; set; } 
} 

[HttpPost] 
// POST: api/Leads 
public bool Post(test objTest) 
{ 
//Do stuff return true; 
}

答案 1 :(得分:1)

您正在向服务器发布数据,但您的参数不是JSON格式,因此您需要使用application/x-www-form-urlencoded对参数进行编码。

尝试:

conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

并查看this