如何使用 setRequestMethod("GET") 接收 JSON?

How can I receive the JSON by using setRequestMethod("GET")?

我想从服务器接收 JSON。所以我使用了 setRequestMethod("GET")。 我已经修改了我的代码几次,但现在还是不行。

package com.example.myapplication;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

//"http://ec2-15-164-98-71.ap-northeast-2.compute.amazonaws.com:8888/code/list"

public class MainActivity extends AppCompatActivity {

    TextView tvData;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvData = findViewById(R.id.textView);
        btn = findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new JSONTask().execute();
            }
        });

    }

    public class JSONTask extends AsyncTask<String, Void, String>{

        @Override
        protected String doInBackground(String... urls) {
            URL url = null;
            try {
                //JSONObject를 만들고 key value 형식으로 값을 저장해준다.
                url = new URL("http://ec2-15-164-98-71.ap-northeast-2.compute.amazonaws.com:8888/code/list");
                JSONObject jsonObject = new JSONObject();
                //jsonObject.accumulate("user_id", "androidTest");
                //jsonObject.accumulate("name", "yun");

                HttpURLConnection con = null;
                BufferedReader reader = null;

                try{
                    con = (HttpURLConnection) url.openConnection();

                    con.setRequestMethod("GET");
                    con.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.146 Whale/2.6.90.18 Safari/537.36");
                    con.setRequestProperty("Accept", "application/json");

                    con.setConnectTimeout(3000);
                    con.setReadTimeout(3000);

                    con.setDoOutput(true);//Outstream으로 post 데이터를 넘겨주겠다는 의미
                    con.setDoInput(true);//Inputstream으로 서버로부터 응답을 받겠다는 의미
                    con.connect();

                    System.out.println(con.getResponseCode());
                    System.out.println(con.getResponseMessage());
                    //서버로 보내기위해서 스트림 만듬
                    OutputStream outStream = con.getOutputStream();
                    //버퍼를 생성하고 넣음
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outStream));
                    writer.write(jsonObject.toString());
                    writer.flush();
                    writer.close();//버퍼를 받아줌

                    //서버로 부터 데이터를 받음
                    InputStream stream = con.getInputStream();

                    reader = new BufferedReader(new InputStreamReader(stream));

                    StringBuffer buffer = new StringBuffer();

                    String line = "";
                    while((line = reader.readLine()) != null){
                        buffer.append(line);
                    }

                    return buffer.toString();//서버로 부터 받은 값을 리턴해줌 아마 OK!!가 들어올것임

                } catch (MalformedURLException e){
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if(con != null){
                        con.disconnect();
                    }
                    try {
                        if(reader != null){
                            reader.close();//버퍼를 닫아줌
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            tvData.setText(result);//서버로 부터 받은 값을 출력해주는 부
        }
    }
}

这是 logcat。 403是getResponseCode()的一个值,Forbidden是getResponseMessage()的结果。 有人说“(HTTPLog)-Static: isSBSettingEnabled false”问题可以通过 asyncTask 来解决。但是我已经在我的代码中使用了 asyncTask。

2020-02-17 16:00:12.480 9517-10273/? I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
2020-02-17 16:00:12.559 9517-10273/? I/System.out: 403
2020-02-17 16:00:12.560 9517-10273/? I/System.out: Forbidden

您需要使用 getInputStream() 而不是 getOutputStream(),因为您从连接读取输入。

PS。不知道为什么你仍然使用 URLConnection。我推荐你使用 OKHttp 连接。比这容易多了。