Http request to web service in java

2019-07-26 21:42发布

问题:

I have the following method in a C# project which builds a web request to consume a web service:

    private HttpWebRequest BuildRequest(string fullUri, object param, RequestMethod method, Dictionary<string, string> requestHeaders)
            {
                HttpWebRequest request = WebRequest.Create(fullUri) as HttpWebRequest;
                request.Method = method.ToString().ToUpper();
                request.Accept = "application/json";
                request.ContentType = "application/json";
                foreach (var h in requestHeaders)
                {
                    request.Headers.Add(string.Format("{0}: {1}", h.Key, h.Value));
                }
                if (method == RequestMethod.Post)
                {
                    JavaScriptSerializer ser = new JavaScriptSerializer();
                    string postData = ser.Serialize(param);
                    request.ContentLength = postData.Length;
                    Stream s = request.GetRequestStream();
                    StreamWriter sw = new StreamWriter(s);
                    sw.Write(postData);
                    sw.Flush();
                }
                return request;
            }

Now I am wanting to do the same thing in Java but cant quite figure out how. So far I have...

private HttpRequestBase BuildRequest(String fullUri, Object param, 
            RequestMethod method, HashMap<String, String> requestHeaders) {
        HttpRequestBase request = null;
        if(method == RequestMethod.GET) {
            request = new HttpGet(fullUri);
        } else if (method == RequestMethod.POST) {
            request = new HttpPost(fullUri);
        }
        request.addHeader(new BasicHeader("Accept", "application/json"));
        request.addHeader(new BasicHeader("ContentType", "application/json"));
        for(Map.Entry<String, String> header : requestHeaders.entrySet()) {
            request.addHeader(new BasicHeader(header.getKey(), header.getValue()));
        }
        return request;
    }

As far as I can tell that looks like it will work but I need to get the request stream like I do in the C# version in order to send an object as json but cant see how to get it. So my question is how to get it from a HttpRequestBase or any other object that I can use to build a HttpRequest in java.

Thanks.

FYI.. RequestMethod is an Enum either GET or POST" And this is in an android application so I am able to use anything in the android sdk.