繁体   English   中英

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

[英]Post json data to REST service using android/httpclient with stream

我在将数据发布到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 }

检查此代码段。 我确实尝试过,但是应该可以

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
}
} 
      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) {
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM