2012-12-13 14 views
-1

我想发送一个字符串数据,“”,以字节格式的服务器在Android应用程序。我使用HttpClient,但我认为它不是正确的方式,请帮助我如何做到这一点?如何以字节格式向服务器发布字符串数据?

在.net的情况下,我想在java中类似的代码。

string boundary = Guid.NewGuid().ToString(); 
    HttpWebRequest request = HttpWebRequest.Create(url) 
     as HttpWebRequest; 
    request.Method = "POST"; 
    //request.ContentType = "application/json"; 
    request.PreAuthenticate = true; 

    byte[] fulldata = Encoding.UTF8.GetBytes(data); 
    request.ContentLength = fulldata.Length; 
    using (Stream sw = request.GetRequestStream()) 
    { 
     sw.Write(fulldata, 0, fulldata.Length); 
    } 
+0

“我认为它不正确的方式” - 你可以尝试:信鸽IP通讯(IPoAC)如果你觉得一个HttpClient的不适合,它具有很高的延迟,但可以在单个数据包中传递大量数据[请参阅http://en.wikipedia.org/wiki/IP_over_Avian_Carriers] –

+0

使用HttpClient可以将字节数据发送到服务器。看到我的答案希望它会帮助你。 –

回答

1

首先你的字符串数据转换为字节,并通过使用ByteArrayEntity字节格式将数据发送到服务器。

尝试这样

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://192.168.1.1/xxx"); 
HttpResponse response; 
HttpParams hp = new BasicHttpParams(); 

//use ByteArrayEntity to send string data in byteformat 
ByteArrayEntity byteEntity = new ByteArrayEntity(byte_data); 
httppost.setEntity(byteEntity); 
response = httpclient.execute(httppost); 
+0

我得到一个错误,java.net.UnknownHostException:xxxx.sitename.com,在线,\t \t \t HttpResponse responseHttpResponse = httpclient.execute(httppost); –

+0

你有没有在清单中使用权限,如

+0

转到此链接.. http://guerrarj.hubpages.com/hub/Tips-to-solve- the-UnknownHostException-on-Android ..可能你有其中一个解决方案的问题.. –

相关问题