【发布时间】:2016-01-30 11:52:24
【问题描述】:
在我使用 Apache 库(org.apach.httpclient)向带有参数(BasicNameValuePair)的 PHP 脚本发出请求之前,
那么现在我想删除那些库以减小 APK 大小,并且还因为它已被弃用,
我尝试了许多解决方案和许多示例,但没有一个有效,
这是我实际使用的代码(没有任何反应):
public JSONObject sendRequest(final String link, final HashMap<String, String> values) {
JSONObject object = null;
Thread thread = new Thread() {
@Override
public void run() {
HttpURLConnection conn;
final int CONNECTION_TIMEOUT = 15 * 1000;
Log.e("Tag", "Start");
try {
URL url = new URL(link);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(CONNECTION_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
Log.e("Tag", "Connect");
if (values != null) {
OutputStream os = conn.getOutputStream();
OutputStreamWriter osWriter = new OutputStreamWriter(os, "UTF-8");
BufferedWriter writer = new BufferedWriter(osWriter);
Log.e("Tag", "Write " + values);
writer.write(getPostData(values));
writer.flush();
writer.close();
os.close();
}
}
catch (MalformedURLException e) {}
catch (IOException e) {}
}
};
thread.start();
return object;
}
调用 sendRequest() :
HashMap<String, String> values = new HashMap<String, String>();
values.put("Test01", "Test");
values.put("Test02", "Test2");
sendRequest("http://TheWebSite/script.php", values);
Php 脚本应该简单地将值写入文件但什么都没有发生(它与 Apache HttpPost 一起使用),
任何解决方案?
谢谢
【问题讨论】:
-
它返回什么,
null或其他什么?? -
@ELITE 这不应该向Android返回任何东西,它是一种“分析”系统,php脚本写入服务器中的一个文件就可以了
-
打印所有异常......你正在处理异常但不打印它......
-
尝试
conn.setRequestProperty("Content-Type", "application/json");并以 JSON 格式发送值而不是HashMap -
@ELITE 日志显示 URL 连接和值已正确写入
标签: android httpurlconnection urlconnection