上传数据到服务器端
public static String StringPostApiByGet(String url1, Map<String, String> params) {
try {
byte[] data = getRequestData(params, "UTF-8").toString().getBytes();//获得请求体
Log.i("text","params"+params.toString());
// 根据地址创建URL对象(网络访问的url)
URL url = new URL(url1);
// HttpURLConnection urlConnection = (HttpURLConnection) new URL(url1).openConnection();
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//设置请求体的长度
urlConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
urlConnection.setRequestMethod("POST");// 设置请求的方式
urlConnection.setReadTimeout(5000);// 设置超时的时间
urlConnection.setConnectTimeout(5000);// 设置链接超时的时间
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
// 获取响应的状态码 404 200 505 302
OutputStream outwritestream = urlConnection.getOutputStream();//创建一个文件输出流
outwritestream.write(data);//将生成的JSON数据写出
outwritestream.close();//关闭输出流
System.out.println("--" + urlConnection.getResponseCode());
if (urlConnection.getResponseCode() == 200) {
// 获取响应的输入流对象
InputStream is = urlConnection.getInputStream();
System.out.println("------------------链接成功-----------------"+url);
String Post = Inputstr2Str_Reader(is, "utf-8");
return Post;
} else {
System.out.println("失败"+url);
System.out.println("------------------链接失败-----------------");
return "0";
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
获得请求体
private static StringBuffer getRequestData(Map<String, String> params, String encode) {
System.out.println("params" + params);
StringBuffer stringBuffer = new StringBuffer(); //存储封装好的请求体信息
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
stringBuffer.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(), encode))
.append("&");
}
stringBuffer.deleteCharAt(stringBuffer.length() - 1); //删除最后的一个"&"
} catch (Exception e) {
e.printStackTrace();
}
return stringBuffer;
}
获取响应的输入流对象
private static String Inputstr2Str_Reader(InputStream in, String encode) {
String str = "";
try {
if (encode == null || encode.equals("")) {
// 默认以utf-8形式
encode = "utf-8";
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in, encode));
StringBuffer sb = new StringBuffer();
while ((str = reader.readLine()) != null) {
sb.append(str).append("\n");
}
return sb.toString();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}