public staticString PostRequest(String URL,String obj) {
String jsonString="";try{//创建连接
URL url = newURL(URL);
HttpURLConnection connection=(HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST"); //设置请求方法
connection.setRequestProperty("Charsert", "UTF-8"); //设置请求编码
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type","application/json");
connection.connect();//POST请求
DataOutputStream out = newDataOutputStream(
connection.getOutputStream());//关键的一步
out.writeBytes(obj);
out.flush();
out.close();//读取响应
if (connection.getResponseCode()==200) {
BufferedReader reader= new BufferedReader(newInputStreamReader(connection.getInputStream()));
String lines;
StringBuffer sb= new StringBuffer("");while ((lines = reader.readLine()) != null) {
lines= new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
jsonString=sb.toString();
reader.close();
}//返回值为200输出正确的响应信息
if (connection.getResponseCode()==400) {
BufferedReader reader= new BufferedReader(newInputStreamReader(connection.getErrorStream()));
String lines;
StringBuffer sb= new StringBuffer("");while ((lines = reader.readLine()) != null) {
lines= new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
jsonString=sb.toString();
reader.close();
}//返回值错误,输出错误的返回信息//断开连接
connection.disconnect();
}catch(MalformedURLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(UnsupportedEncodingException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e) {//TODO Auto-generated catch block
e.printStackTrace();
}returnjsonString;
}