【问题标题】:Post json data to REST service using android/httpclient with stream使用带有流的 android/httpclient 将 json 数据发布到 REST 服务
【发布时间】:2012-04-20 14:56:34
【问题描述】:

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

【问题讨论】:

  • 你用java走了多远?
  • 不确定你在问什么,但我实际上已经能够使用 HttpClient 执行 GET,只需要让 POST 工作。
  • post 的工作方式相同,你只需要给它一个实体(可以是很多不同的东西)
  • 不,当方法需要流时不是。这就是关键,流。我的服务方法不只是期待一个 json 对象,(即“application/json”内容类型)他们期待一个流(“application/x-www-form-urlencoded”)
  • 这可能就是 InputStreamEntity 的用途

标签: android json http rest


【解决方案1】:

检查此代码 sn-p。 我确实试过了,但它应该可以工作

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

【讨论】:

  • 那行不通。您没有将流作为请求正文发送。我将发布一个 WCF 方法以进行澄清。
  • 打开 HTTP 连接和 POST 字符串
  • 是的,这就是我想要做的,但我不知道如何将它作为 STREAM 发送。你能举个例子吗?
【解决方案2】:
      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) {
    }

【讨论】:

  • 这看起来像我需要的,但我对你拥有的几个变量感到困惑。 'urls'和'reply'是什么类型。
  • 有没有办法用http客户端做到这一点?我必须进行 NTLM 身份验证,并且我有自定义的 socketfactories 和 schemefactories 可以做到这一点。使用 HttpURLConnection 的方式或某种方式。
  • 如何使用这个发送特殊字符?我尝试使用它确实帮助了我 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); connection.setRequestProperty("Content-Length",String.valueOf(strJsonRequest.toString().getBytes().length));
猜你喜欢
  • 1970-01-01
  • 2011-02-02
  • 2018-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-17
  • 1970-01-01
相关资源
最近更新 更多