使用带有流的android / httpclient将json数据发布到REST服务

时间:2012-04-20 14:56:35

标签: android json http rest

我在将数据发布到REST WCF服务时遇到了一些困难。我需要向它发送一个json对象/数组,但我的POST方法需要一个Stream,然后将其拆分以获取JSON(不能更改此部分)。

我已在C#中使用以下代码完成此操作:

    public static string CallPostService(string url, string data)
    {
        url = Config.serviceAddress + url;
        string json = data;
        byte[] buffer = Encoding.UTF8.GetBytes(json);
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = "POST";
        request.Credentials = new NetworkCredential("user", "pass");
        request.ContentType = "application/x-www-form-urlencoded";
        using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
        {
            sw.Write(json);
            Console.WriteLine(json);
        }
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
        {
            string res = sr.ReadToEnd();
            return res;
        }
    }

我需要一些等效的Java代码来执行此操作,最好使用Apache HttpClient。我是http库的新手,所以我很欣赏一点方向。

编辑:

以下是我的WCF服务的方法标头。请求正文需要是一个流,因此服务可以处理它。

[WebInvoke(Method = "POST", UriTemplate = "person/delete", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Person DeletePerson(Stream streamdata) { //bla }

2 个答案:

答案 0 :(得分:0)

检查此代码段。 我真的试过了,但它应该有用

public void postData() {
try {    
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
String auth = android.util.Base64.encodeToString(
(username + ":" + password).getBytes("UTF-8"), 
android.util.Base64.NO_WRAP
 );
 httppost.addHeader("Authorization", "Basic "+ auth);

    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}
} 

答案 1 :(得分:0)

      String MyData;// Data need to post to server JSON/XML
      String reply;  
      try {

        URLConnection connection = url.openConnection(); 
        HttpURLConnection httppost = (HttpURLConnection) connection;
        httppost.setDoInput(true); 
        httppost.setDoOutput(true); 
        httppost.setRequestMethod("POST"); 
        httppost.setRequestProperty("User-Agent", "UA Here"); 
        httppost.setRequestProperty("Accept_Language", "en-US"); 
        httppost.setRequestProperty("Content-Type", "content type here"); 
        DataOutputStream dos = new DataOutputStream(httppost.getOutputStream()); 
        dos.write(MyData.getBytes()); // bytes[] b of post data 

        InputStream in = httppost.getInputStream(); 
        StringBuffer sb = new StringBuffer(); 
        try { 
            int chr; 
            while ((chr = in.read()) != -1) { 
                sb.append((char) chr); 
            } 
            reply = sb.toString(); 
        } finally { 
            in.close(); 
        } 

        Log.v("POST RESPONSE",reply);

    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }