【已解决】 我在练习post提交文本内容,使用的是摸鱼评论的API,不知道为什么,点击按钮后没有反应
package com.example.androidnetwork;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import com.example.androidnetwork.entity.CommentItem;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostTestActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "ning";
private InputStream inputStream;
private OutputStream outputStream;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_test);
findViewById(R.id.btn_post).setOnClickListener(this);
}
@Override
public void onClick(View v) {
new Thread(() -> {
inputStream = null;
outputStream = null;
if (R.id.btn_post == v.getId()) {
try {
URL url = new URL("https://api.sunofbeaches.com/ct/moyu/comment");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
//设置链接超时时间
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
httpURLConnection.setRequestProperty("Accept", "application/json,text/plain, */*");
CommentItem commentItem = new CommentItem("1688", "夜色难免微凉,前行必有曙光");
Gson gson = new Gson();
String json = gson.toJson(commentItem);
byte[] bytes = json.getBytes("UTF-8");
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(bytes.length));
//连接
httpURLConnection.connect();
outputStream = httpURLConnection.getOutputStream();
outputStream.write(bytes);
outputStream.flush();
//拿结果
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
Log.d(TAG, "result--->" + bufferedReader.readLine());
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
});
}
}

你的线程没有start() , 当然没反应了
打断点