반응형

HTTP 요청을 보내고 응답을 받아 보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using System.Net.Http;
 
namespace ConsoleApp1
{
    class Program
    {
        // HttpClient is intended to be instantiated once per application, rather than per-use.
        static readonly HttpClient httpClient = new HttpClient();
 
        static async Task Main(string[] args)
        {
            try
            {
                Console.Write("Enter URI: ");
                string uriString = Console.ReadLine();
 
                HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(uriString.Trim());
                httpResponseMessage.EnsureSuccessStatusCode();
                // Throws an exception if the IsSuccessStatusCode property for the HTTP response is false.
                string responseBody = await httpResponseMessage.Content.ReadAsStringAsync();
                // Above three lines can be replaced with new helper method below
                //string responseBody = await httpClient.GetStringAsync(uriString.Trim());
 
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

원하는 URI를 입력하면 데이터가 출력된다.

 

반응형
Posted by J-sean
:
반응형

Everything에는 http server, ftp server를 만들 수 있는 기능이 있다. http server를 이용해 간단히 원하는 파일이나 폴더를 공유해 보자. (ftp server도 거의 비슷한 방법으로 만들 수 있다)

 

Everything이 설치되어 있다.

 

Options...를 클릭한다.

 

HTTP Server를 선택한다. (ETP/FTP Server도 비슷한 방식으로 만들면 된다)

 

Enable HTTP server를 선택하고 Username과 Password를 입력한다.

 

 

Indexes - Exclude를 선택한다.

 

Enable exclude list를 선택하고 Add Folder... 버튼을 클릭해 공유(검색)에서 제외할 폴더나 드라이브를 선택한다.

 

Apply 버튼과 OK 버튼을 클릭한다.

 

인터넷 브라우저 주소창에 localhost를 입력한다.

 

 

아니면 127.0.0.1을 입력하고 사용자이름과 비밀번호를 입력한다.

 

제외된 C~H 드라이브 빼고 I 드라이브만 표시된다.

 

검색창에 폴더명이나 파일명을 입력해서 찾을 수 도 있다.

 

공유기를 사용한다면 포트포워드 설정으로 외부에서도 파일을 공유할 수 있다.

 

 

Options - Indexes - NTFS - Settings for XXX - Include in database 에서 공유(검색) 드라이브를 추가하거나 제외할 수 도 있다.

 

필요하다면 subst 명령으로 원하는 폴더를 드라이브로 지정하고 그 드라이브만 database에 추가해서 공유한다.

 

반응형
Posted by J-sean
:
반응형

웹서버에 데이터를 요청하고 app에서 응답 받아 처리할 수 있다.


서버에서 전달 되는 데이터 형식(Json)

1
2
3
4
5
6
7
8
9
10
11
12
13
{
    "LastUpdate":"2019.10.12",
    "SalesRecord":
    [
        {"date":"2016.03.08","item":"apple","price":2400,"quantity":84,"total":201600},
        {"date":"2016.07.29","item":"grape","price":3100,"quantity":37,"total":114700},
        {"date":"2017.10.25","item":"peach","price":4600,"quantity":55,"total":253000},
        {"date":"2018.12.08","item":"banana","price":1500,"quantity":83,"total":124500},
        {"date":"2019.05.09","item":"melon","price":7200,"quantity":75,"total":540000},
        {"date":"2019.10.17","item":"coconut","price":6800,"quantity":59,"total":401200},
        {"date":"2019.11.07","item":"strawberry","price":4900,"quantity":30,"total":147000}
    ]
}



<AndroidManifest.xml>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    <uses-permission android:name="android.permission.INTERNET"/>
 
    <application
        android:usesCleartextTraffic="true">
        <!--
        android:usesCleartextTraffic
        Indicates whether the app intends to use cleartext network traffic, such as cleartext HTTP.
        The default value for apps that target API level 27 or lower is "true". Apps that target
        API level 28 or higher default to "false". When the attribute is set to "false", platform
        components (for example, HTTP and FTP stacks, DownloadManager, and MediaPlayer) will refuse
        the app's requests to use cleartext traffic. Third-party libraries are strongly encouraged
        to honor this setting as well. The key reason for avoiding cleartext traffic is the lack of
        confidentiality, authenticity, and protections against tampering; a network attacker can
        eavesdrop on transmitted data and also modify it without being detected.
        -->



<MainActivity.java>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
public class MainActivity extends AppCompatActivity {
 
    EditText editText;
    TextView textView;
 
    static RequestQueue requestQueue;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);
 
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                makeRequest();
            }
        });
 
        if (requestQueue == null) {
            requestQueue = Volley.newRequestQueue(getApplicationContext());
        }
    }
 
    public void makeRequest() {
        String url = editText.getText().toString();
        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            //Server(Ubuntu) data encoding
                            response = new String(response.getBytes("iso-8859-1"), "utf-8");
                            //textView.append("Raw data: " + response);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
 
                        Gson gson = new Gson();
                        RequestResult requestResult = gson.fromJson(response, RequestResult.class);
                        textView.setText("Items count: " + requestResult.SalesRecord.size() + '\n');
                        textView.append("Last Update: " + requestResult.LastUpdate + '\n');
                        ArrayList<Data> items = requestResult.SalesRecord;
                        for (int i = 0; i < items.size(); i++) {
                            textView.append(String.format("■ Date: %s, Item: %s, Price: %s, Quantity: %s, Total: %s\n",
                                    items.get(i).date, items.get(i).item, items.get(i).price, items.get(i).quantity, items.get(i).total));
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        textView.append("Error: " + error.getMessage());
                    }
                }
        ) {
            @Override
            protected Map<StringString> getParams() throws AuthFailureError {
                Map<StringString> params = new HashMap<StringString>();
 
                return params;
            }
        };
 
        request.setShouldCache(false);
        requestQueue.add(request);
        textView.setText("Request sent.");
    }
}




<RequestResult.java>

1
2
3
4
public class RequestResult {
    String LastUpdate;
    ArrayList<Data> SalesRecord = new ArrayList<Data>();
}


서버 데이터의 key와 같은 이름의 변수를 만들어야 한다.


<Data.java>

1
2
3
4
5
6
7
public class Data {
    String date;
    String item;
    String price;
    String quantity;
    String total;
}


서버 데이터의 key와 같은 이름의 변수를 만들어야 한다


실행 화면. 서버 주소를 입력하고 DATA REQUEST 버튼을 클릭한다.


서버부터 전달된 데이터가 지정한 대로 표시된다.


반응형
Posted by J-sean
: