无Unity分享一个古老的Android通信http类
Posted avi9111
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无Unity分享一个古老的Android通信http类相关的知识,希望对你有一定的参考价值。
现在早不流行这么干了,下面代码是一些“祖传”的方法
随着android支持https,这样的方法,可能会带来一些 隐患
不过,为了避免引入第三方包,或者避免冲突
选了一个老人才会的“偏方”
调用方法
String json = "";
FormFieldKeyValuePair item = new FormFieldKeyValuePair();
item.setKey("msgContent");
item.setValue(json);
arr.add(item);
try {
String url = DMMLaunchUtility.GetUrl();
HttpUtility.sendHttpPost(url, arr);
} catch (Exception e) {
e.printStackTrace();
}
源码
public class HttpUtils
{
public static String sendHttpPost(String serverUrl, ArrayList<FormFieldKeyValuePair> generalFormFields) throws Exception {
// 向服务器发送post请求
URL url = new URL(serverUrl/* "http://127.0.0.1:8080/test/upload" */);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 发送POST请求必须设置如下两行
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY);
// 头
String boundary = BOUNDARY;
// 传输内容
StringBuffer contentBody = new StringBuffer("--" + BOUNDARY);
// 尾
String endBoundary = "\\r\\n--" + boundary + "--\\r\\n";
OutputStream out = connection.getOutputStream();
// 处理文字形式的POST请求
for (FormFieldKeyValuePair ffkvp : generalFormFields) {
contentBody.append("\\r\\n")
.append("Content-Disposition: form-data; name=\\"")
.append(ffkvp.getKey() + "\\"")
.append("\\r\\n")
.append("\\r\\n")
.append(ffkvp.getValue())
.append("\\r\\n")
.append("--")
.append(boundary);
}
String boundaryMessage1 = contentBody.toString();
out.write(boundaryMessage1.getBytes("utf-8"));
out.write(endBoundary.getBytes("utf-8"));
out.flush();
out.close();
// 从服务器获得回答的内容
String strLine = "";
String strResponse = "";
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while ((strLine = reader.readLine()) != null) {
strResponse += strLine + "\\n";
}
// System.out.print(strResponse);
return strResponse;
}
}
以上是关于无Unity分享一个古老的Android通信http类的主要内容,如果未能解决你的问题,请参考以下文章