2016-03-03 22 views
1

经过一段时间的研究后,我还没有找到任何包含我的问题的解决方案。在Android/Java中将HttpUrlConnection作为二进制/八位字节进行POST字符串数据

我有一个String价值,我想通过POST发送它。

我已经建立了一些东西。我只是不知道如何设置它将作为二进制/八位字节流发送。

String data = someData(); 
String sUrl = "http://some.example.website.com"; 
URL url = new URL(sUrl); 
HttpURLConnection connection = (HttpURLConnection) (new URL(sUrl)).openConnection(); 
connection.setRequestMethod("POST"); 
connection.setDoOutput(true); 
connection.setDoInput(true); 
connection.connect(); 

我使用HttpUrlConnection因为我用DefaultHttpClient()使用已过时。

我希望有人能帮帮我!

亲切的问候!

+0

你得到的错误是什么?您也可以使用DefaultHttpClient(),尽管它已被弃用。如果你想我可以分享我在我的应用程序中使用的DefaultHttpClient()代码。 – Sid

+0

是的,请分享。我以为我用HttpUrlConnection替换DefaultHttpClient()。正如我看到我做不到的,我想要的。请分享您的代码 – raymondis

回答

1

您可以使用类似的代码下面的代码片段:

HttpClient httpclient = new DefaultHttpClient(); 

String responseXml = null; 
StringEntity se = "test string to be sent to the server"; 


HttpPost httppost = new HttpPost(temp); 
try { 
    se.setContentType("text/soap+xml"); 
    httppost.setEntity(se); 
    HttpResponse httpresponse = httpclient.execute(httppost); 
    HttpEntity resEntity = httpresponse.getEntity(); 
    responseXml = EntityUtils.toString(resEntity); 
    Log.d("Response XML", responseXml); 
} catch (UnsupportedEncodingException e) { 
    e.printStackTrace(); 
    Log.e(TAG,e.getMessage()); 
} catch (ClientProtocolException e) { 
    Log.e(TAG,e.getMessage()); 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
    Log.e(TAG, e.getMessage()); 
} catch (Exception e){ 
    e.printStackTrace(); 
    Log.e(TAG,e.getMessage()); 
} 

我用这个代码到一个XML发送到服务器。您可以替换您想要在se变量中发送的内容。

相关问题