如何通过httpurlconnection发送Android资产文件?

时间:2015-03-26 06:04:38

标签: android httpurlconnection

我在资产文件夹中有一个text / plain文件。我想通过httpurlconnection将此文件作为字符串或建议发送。怎么做。 我的代码如下:

  java.net.URL url = new URL("https://xx.xx.xx.xxx");
                HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();
                urlConnection.setSSLSocketFactory(getSSLSocketFactory());
                urlConnection.setRequestMethod("POST");
                urlConnection.setReadTimeout(15*10000);
                urlConnection.connect();

                AssetManager assetManager = MainActivity.ctx.getAssets();
                InputStream requestXML = assetManager.open("requestdump");

                String requestString = convertStreamToString(requestXML);

                InputStream in = urlConnection.getInputStream();
                convertStreamToString(in);

请建议如何通过httpurlconnection发送资产文本文件?

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

用它来发送字符串

URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1));

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();


private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}