关于Android利用POST连接服务器之间的数据的发送 50

privatevoidgetDataPost(){JSONObjectjsonObject=newJSONObject();try{jsonObject.put("typ... private void getDataPost(){ JSONObject jsonObject = new JSONObject(); try { jsonObject.put("type", DataValue.ALL); String json = String.valueOf(jsonObject); // 将json数据转化成字符串发送出去 HttpURLConnection connection = HttpConnection.getConnection(ServerUrl.URL); // 往服务器里面发送数据 if (jsonObject != null && connection!=null) { byte[] writebytes = json.getBytes(); // 设置文件长度 connection.setRequestProperty("Content-Length", String.valueOf(writebytes.length)); OutputStream outwritestream = connection.getOutputStream(); outwritestream.write(json.getBytes()); Log.d("hlhupload", "doJsonPost: conn"+connection.getResponseCode()); String result = NetUntil.readString(connection.getInputStream()); // 然后我们把json转换成JSONObject类型 if(result!=null&&!"".equals(result) || connection.getResponseCode() == 200){ //TODO Log.e("error"," Received information is empty "); }else{ getJsonData(result); } outwritestream.flush(); outwritestream.close(); connection.disconnect(); }else{ Log.e("ConnectionException","Connection to server failed"); } } catch (Exception e) { Log.e("IOException",e.getMessage()); } }``` ```public static HttpURLConnection getConnection (String url){ HttpURLConnection connection ; try { connection= (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(5000); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Charset", "UTF-8"); connection.setRequestProperty("Content-Type","application/json; charset=UTF-8"); connection.setRequestProperty("accept","application/json"); return connection ; } catch (Exception e) { Log.e("error",e.getMessage()); return null ; } }这个是我写的一个android这边利用post方式,向服务器发送数据,但是不知道为社么就是发不出去。调试今后,他跑了一个异常给我。不是很懂这个异常,网上也没找到这种。之前看网上,也是这样做的连接,但不知道为啥到我这就不行了。 展开
 我来答
爱唐伯虎点文香
2018-05-14 · TA获得超过3.3万个赞
知道大有可为答主
回答量:1778
采纳率:94%
帮助的人:173万
展开全部
private void toUploadFile(File file, String fileKey, String RequestURL,
Map<String, String> param) {
imgUrl = null;
String result = null;
requestTime = 0;
conn = null;
long requestTime = System.currentTimeMillis();
long responseTime = 0;

try {
URL url = new URL(RequestURL);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(readTimeOut);
conn.setConnectTimeout(connectTimeout);
conn.setDoInput(true); // 允许输入流
conn.setDoOutput(true); // 允许输出流
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST"); // 请求方式
conn.setRequestProperty("Charset", CHARSET); // 设置编码

if (APPConfiguration.USER_LOADING == 1) {
conn.setRequestProperty("platform", APP_TOSERVER.Platform);
} else if (APPConfiguration.USER_LOADING == 2) {
conn.setRequestProperty("userId", APP_TOSERVER.UserId);
conn.setRequestProperty("userToken", APP_TOSERVER.UserToken);
conn.setRequestProperty("machineImei", APP_TOSERVER.MachineImei);
conn.setRequestProperty("version", APP_TOSERVER.Version);
conn.setRequestProperty("platform", APP_TOSERVER.Platform);
}

conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
+ BOUNDARY);
// conn.setRequestProperty("enctype", "multipart/form-data");

/**
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
StringBuffer sb = null;
String params = "";

/***
* 以下是用于上传参数
*/
if (param != null && param.size() > 0) {
Iterator<String> it = param.keySet().iterator();
while (it.hasNext()) {
sb = null;
sb = new StringBuffer();
String key = it.next();
String value = param.get(key);
sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
sb.append("Content-Disposition: form-data; name=\"")
.append(key).append("\"").append(LINE_END)
.append(LINE_END);
sb.append(value).append(LINE_END);
params = sb.toString();
Log.i(TAG, key + "=" + params + "##");
dos.write(params.getBytes());
dos.flush();
}
}

sb = null;
params = null;
sb = new StringBuffer();
/**
* 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/
sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
sb.append("Content-Disposition:form-data; name=\"" + fileKey
+ "\"; filename=\"" + file.getName() + "\"" + LINE_END);
sb.append("Content-Type:image/pjpeg" + LINE_END); // 这里配置的Content-type很重要的
// ,用于服务器端辨别文件的类型的
sb.append(LINE_END);
params = sb.toString();
sb = null;

Log.i(TAG, file.getName() + "=" + params + "##");
dos.write(params.getBytes());
/** 上传文件 */
InputStream is = new FileInputStream(file);
onUploadProcessListener.initUpload((int) file.length());
byte[] bytes = new byte[1024];
int len = 0;
int curLen = 0;
while ((len = is.read(bytes)) != -1) {
curLen += len;
dos.write(bytes, 0, len);
Log.i(TAG, "curLen:" + curLen);
onUploadProcessListener.onUploadProcess(curLen);
}
is.close();

dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
.getBytes();
dos.write(end_data);
dos.flush();
//
// dos.write(tempOutputStream.toByteArray());
/**
* 获取响应码 200=成功 当响应成功,获取响应的流
*/
int res = conn.getResponseCode();
responseTime = System.currentTimeMillis();
this.requestTime = (int) ((responseTime - requestTime) / 1000);
Log.e(TAG, "response code:" + res);
if (res == 200) {
Log.e(TAG, "request success");
BufferedReader input = new BufferedReader(
new InputStreamReader(conn.getInputStream(), CHARSET));
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
Log.e(TAG, "result : " + handleString(result));
readJSON(handleString(result));
sendMessage(UPLOAD_SUCCESS_CODE, "上传结果:" + handleString(result));
return;
} else {
Log.e(TAG, "request error");
sendMessage(UPLOAD_SERVER_ERROR_CODE, "上传失败:code=" + res);
return;
}
} catch (MalformedURLException e) {
disconnection();
sendMessage(UPLOAD_SERVER_ERROR_CODE,
"上传失败:error=" + e.getMessage());
Log.e(TAG, "上传失败:error=" + e.getMessage());
e.printStackTrace();
return;
} catch (IOException e) {
disconnection();
sendMessage(UPLOAD_SERVER_ERROR_CODE,
"上传失败:error=" + e.getMessage());

Log.e(TAG, "上传失败:error=" + e.getMessage());
e.printStackTrace();
return;
} catch (Exception e) {
e.printStackTrace();
disconnection();
sendMessage(UPLOAD_SERVER_ERROR_CODE,
"上传失败:error=" + e.getMessage());

Log.e(TAG, "上传失败:error=" + e.getMessage());
}
}
威孚半导体技术
2024-08-19 广告
威孚(苏州)半导体技术有限公司是一家专注生产、研发、销售晶圆传输设备整机模块(EFEM/SORTER)及核心零部件的高科技半导体公司。公司核心团队均拥有多年半导体行业从业经验,其中技术团队成员博士、硕士学历占比80%以上,依托丰富的软件底层... 点击进入详情页
本回答由威孚半导体技术提供
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式