public void postRequest(View view) {
new Thread(new Runnable() {
@Override
public void run() {
OutputStream outputStream = null;
InputStream inputStream = null;
try {
URL url = new URL(BASE_URL+"/post/comment");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(10000);
connection.setRequestProperty("Content-Type","application/json;charset=UTF-8");
CommandItem commandItem = new CommandItem("2341","mark...");
Gson gson = new Gson();
String json = gson.toJson(commandItem);
byte[] bytes = json.getBytes("UTF-8");
Log.e(TAG, "run: "+bytes.length );
connection.setRequestProperty("Content-Length",String.valueOf(bytes.length));
//连接
connection.connect();
//数据给出去
outputStream = connection.getOutputStream();
outputStream.write(bytes);
outputStream.flush();
//拿到结果
int responseCode = connection.getResponseCode();
Log.e(TAG, "run: "+responseCode );
if (responseCode == 200){
inputStream = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line = br.readLine();
Log.e(TAG, "run: "+line );
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (outputStream!=null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream!=null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
网友评论