๊ด€๋ฆฌ ๋ฉ”๋‰ด

ruriruriya

[Android] ์•ˆ๋“œ๋กœ์ด๋“œ - Volley์—์„œ Header์— ๋ฐ์ดํ„ฐ ์„ธํŒ…ํ•˜๋Š” ๋ฐฉ๋ฒ• ๋ณธ๋ฌธ

๐Ÿค–Android/Java

[Android] ์•ˆ๋“œ๋กœ์ด๋“œ - Volley์—์„œ Header์— ๋ฐ์ดํ„ฐ ์„ธํŒ…ํ•˜๋Š” ๋ฐฉ๋ฒ•

๋ฃจ๋ฆฌ์•ผใ…‘ 2024. 1. 4. 00:34
๋ฐ˜์‘ํ˜•

ํŒŒํŒŒ๊ณ  API๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด์„œ ์‹œํฌ๋ฆฟ ํ‚ค๋ฅผ Volley Header์— ๋ฐ์ดํ„ฐ๋ฅผ ์„ธํŒ…ํ•ด๋ณด์ž.

 

1.Config ํŒจํ‚ค์ง€ - config.java ์ƒ์„ฑ

์•ˆ๋“œ๋กœ์ด๋“œ ์•ฑ์—์„œ Config.java ๋˜๋Š” Constants.java์™€ ๊ฐ™์€ ํŒŒ์ผ์€ ์•ฑ ์ „๋ฐ˜์— ๊ฑธ์ณ ์‚ฌ์šฉ๋˜๋Š” ์ƒ์ˆ˜, ์„ค์ • ๊ฐ’, ํ‚ค, URL ๋“ฑ์„ ๋‹ด๋Š” ๋ฐ ์‚ฌ์šฉ๋œ๋‹ค. ์ด ํŒŒ์ผ์€ ์•ฑ์˜ ๊ตฌ์„ฑ์„ ๊ด€๋ฆฌํ•˜๊ณ  ๋ณ€๊ฒฝ์ด ํ•„์š”ํ•œ ๊ฐ’๋“ค์„ ํ•œ ๊ณณ์— ๋ชจ์•„๋‘์–ด ๊ด€๋ฆฌํ•˜๊ธฐ ์‰ฝ๊ฒŒ ํ•œ๋‹ค.

2. config.java

๋„ค์ด๋ฒ„ ํด๋ผ์ด์–ธํŠธ ์•„์ด๋””์™€ ์‹œํฌ๋ฆฟ ํ‚ค๋ฅผ ์“ด๋‹ค.

์ด๋•Œ ๋ณ€์ˆ˜๋ช…์€ ๋Œ€๋ฌธ์ž์— ์–ธ๋”๋ฐ”๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

public class Config {

    public static final String X_NAVER_CLIENT_ID = "X-Naver-Client-Id";
    public static final String X_NAVER_CLIENT_SECRET = "X-Naver-Client-Secret";

}

 

3. ์‹œํฌ๋ฆฟ ํ‚ค header ์‚ฝ์ž…

JsonObjectRequest์˜ ํŒŒ๋ผ๋ฏธํ„ฐ ๋’ค์— ์ž‘์„ฑํ•œ๋‹ค.

RequestQueue queue = Volley.newRequestQueue(MainActivity.this);

String url = "https://openapi.naver.com/v1/papago/n2mt";

JSONObject body = new JSONObject();
try {
    body.put("source", "en");
    body.put("target", target);
    body.put("text", sentence);
} catch (JSONException e) {
    // ์œ ์ €ํ•œํ…Œ ์•Œ๋ ค์ฃผ๊ณ 
    return;
}

JsonObjectRequest request = new JsonObjectRequest(
        Request.Method.POST,
        url,
        body,// body์— ๋“ค์–ด๊ฐˆ ๋ฐ์ดํ„ฐ
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    String result = response.getJSONObject("message").getJSONObject("result").getString("translatedText");

                    txtResult.setText(result);

                    History history = new History(sentence, result, target);
                    historyArrayList.add(0,history); // ์ตœ์‹ ์ด ์ฒซ๋ฒˆ ์งธ์— ๋‚˜์˜ค๋„๋ก.



                } catch (JSONException ex) {
                    // ์œ ์ €์—๊ฒŒ ์•Œ๋ฆฌ๊ณ 
                    return;
                }
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }

) {
    // ๋„ค์ด๋ฒ„ ์‹œํฌ๋ฆฟ ํ‚ค. header ์‚ฝ์ž…๋ฐฉ๋ฒ•


    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new HashMap<>();
        headers.put("X-Naver-Client-Id", Config.X_NAVER_CLIENT_ID);
        headers.put("X-Naver-Client-Secret", Config.X_NAVER_CLIENT_SECRET);
        return headers;
    }
};

queue.add(request);

 

๋ฐ˜์‘ํ˜•