我尝试使用Android中的Post方法从Web服务器发送和接收数据。
这是我的网址调用方法:
InputStream input = null;
OutputStream output = null;
DataOutputStream printout;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(180000);
connection.setConnectTimeout(180000);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestMethod("POST");
connection.connect();
JSONObject jsonParam = new JSONObject();
jsonParam.put("IMEI",IMEI);
PackageManager manager = this.context.getPackageManager();
PackageInfo info = null;
try {
info = manager.getPackageInfo(
this.context.getPackageName(), 0);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String version = info.versionName;
jsonParam.put("Version",version);
byte[] data_ = null;
try {
data_ = jsonParam.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
String base64 = Base64.encodeToString(data_, Base64.DEFAULT);
printout = new DataOutputStream(connection.getOutputStream ());
printout.writeBytes(base64);
printout.flush ();
printout.close ();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
String APK_PATH = Environment.getExternalStorageDirectory() + "/download/";
File dir = new File (APK_PATH);
dir.mkdirs();
File _file = new File(dir, "mynew.apk");
boolean deleted = _file.delete();
output = new FileOutputStream(_file);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
并从服务器返回417异常。
即时通讯使用webapi + squid代理。 我也把这一行放在我的webconfig中:
<system.net>
<settings>
<servicePointManager expect100Continue="false" />
</settings>
</system.net>
但它没有帮助。
在SO中有人解决了这个问题:
HttpClient httpclient = new DefaultHttpClient();
HttpParams params = httpclient.getParams();
params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,false);
但是如何在HttpURLConnection中使用HttpParams?!
答案 0 :(得分:0)
只需将此静态属性从System.Net
设置为false
:
System.Net.ServicePointManager.Expect100Continue = false;
受this answer的启发。