dongliu6848 2015-06-25 12:50
浏览 292

HttpURLConnection setRequestMethod无法正常工作

I'm trying to consume an API rest made with Laravel 4, but when I try to create a new resource (store, POST method) I get response of index function (GET method).

I don't know whats happening with my code:

public static String sendInfo(HashMap<String, String> headers) {
    URL url;
    HttpURLConnection urlConnection = null;
    StringBuilder stringBuilder = new StringBuilder();
    try {
        url = new URL(headers.get("URL"));

        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod(headers.get("method"));

        // Loop hashmap and apply headers
        for (HashMap.Entry<String, String> entry : headers.entrySet()) {
            // I only need the headers with real information. URL and method headers are only for the setRequestMethod and the object URL.
            if (!entry.getKey().equals("URL") && !entry.getKey().equals("method")) {
                urlConnection.addRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        if (urlConnection.getResponseCode() == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            reader.close();
        } else {
            Log.d("sendInfo", "ERROR " + headers.get("URL") + "  STATE: " + urlConnection.getResponseCode());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            urlConnection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
            Log.d("sendInfo", "ERROR DISCONNECT: " + e.getLocalizedMessage());
        }
    }
    Log.d("RESPONSE", "SERVER RESPONSE: "+stringBuilder.toString());

    return stringBuilder.toString();
}

I call this method as follow:

HashMap<String, String> headers = new HashMap<String, String>();
headers.put("URL", "http://foo.com/api/person/");
headers.put("method", "POST");
headers.put("name", "Jason");
headers.put("lastname", "Harrison");
sendInfo(headers);

​But intead of entry in the store function of my Laravel resource, I'm getting the response of the index​ function.

​I put this code in my index to check the http method:

​dd("Index: ".$_SERVER['REQUEST_METHOD']);​

​And returns "GET", so something is wrong in my code​​. All works well with PUT and GET http methods, it only fail with POST

I confirm that the empty body is not the problem, being that I try that.

May somebody could try my code, please?

I'm fully desperate. I only ask you, test my code and guide me in the right direction, please...

  • 写回答

1条回答 默认 最新

  • douwen4178 2015-06-25 13:20
    关注

    You should take a look at retrofit. This lib would make your api call much more cleaner and avoid all those problems you encounter building your request on top of HttpURLConnection.

    EDIT: If you want to do the request by yourself take a look at this post. The problem is very similar to yours. It seems that you need to send data in you request body. Btw sending your parameters via headers isn't a good way to go. I think there might be some lenght restriction plus you might encounter some encoding issues.

    Headers should be used for http related information or just for tokens. You should use body to send your data. Data are most of the time sent using json/xml or httpurlencoded params.

    Edit 2:

    I tried your exact same code with a wamp server and $_SERVER['REQUEST_METHOD'] returned POST. So maybe this issue commes from your server. Try testing you server api with post man chrome plugin to see from which side you error comes from.

    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题