programing

Android에서 Post 매개 변수를 사용하여 HttpClient 및 HttpPost 사용

easyjava 2023. 2. 28. 23:50
반응형

Android에서 Post 매개 변수를 사용하여 HttpClient 및 HttpPost 사용

데이터를 가져와서 Json으로 패키징하고 웹 서버에 올리면 다시 json으로 응답하는 Android 어플리케이션의 코드를 쓰고 있습니다.

GET 요구를 사용하면 정상적으로 동작합니다만, 어떠한 이유로 POST 를 사용하면, 모든 데이터가 삭제되어 서버는 아무것도 수신되지 않습니다.

다음은 코드의 일부입니다.

HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);        
DefaultHttpClient httpClient = new DefaultHttpClient(params);
BasicCookieStore cookieStore = new BasicCookieStore();
httpClient.setCookieStore(cookieStore);

String uri = JSON_ADDRESS;
String result = "";
String username = "user";
String apikey = "something";
String contentType = "application/json";

JSONObject jsonObj = new JSONObject();

try {
    jsonObj.put("username", username);
    jsonObj.put("apikey", apikey);
} catch (JSONException e) {
    Log.e(TAG, "JSONException: " + e);
}

HttpPost httpPost = new HttpPost(uri);
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json", jsonObj.toString()));
HttpGet httpGet = null;
try {
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
    entity.setContentEncoding(HTTP.UTF_8);
    entity.setContentType("application/json");
    httpPost.setEntity(entity);

    httpPost.setHeader("Content-Type", contentType);
    httpPost.setHeader("Accept", contentType);
} catch (UnsupportedEncodingException e) {
    Log.e(TAG, "UnsupportedEncodingException: " + e);
}

try {
    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();

    if (httpEntity != null) {
        InputStream is = httpEntity.getContent();
        result = StringUtils.convertStreamToString(is);
        Log.i(TAG, "Result: " + result);
    }
} catch (ClientProtocolException e) {
    Log.e(TAG, "ClientProtocolException: " + e);
} catch (IOException e) {
    Log.e(TAG, "IOException: " + e);
}

return result;

파라미터를 작성하고 게시하는 방법에 대한 일반적인 가이드라인을 따랐다고 생각합니다만, 실제로는 그렇지 않은 것 같습니다.

이 시점에서 솔루션을 찾을 수 있는 위치에 대한 도움말이나 포인터는 매우 환영입니다(포스트 데이터가 전송되지 않은 것을 깨닫고 몇 시간을 보낸 후).실제 서버는 Tomcat에서 Wicket을 실행하고 있지만, 간단한 PHP 페이지에서 테스트해 보았습니다.

실제로는, 다음의 방법으로 JSON으로서 송신할 수 있습니다.

// Build the JSON object to pass parameters
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("apikey", apikey);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);

JSON 오브젝트 없이 실행하려고 했는데, 2개의 기본 이름 값 페어를 통과한 적이 있습니까?또한 서버 설정과 관련이 있을 수 있습니다.

업데이트: 다음 코드를 사용합니다.

InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate)); 

try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(connection);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.d("HTTP", "HTTP: OK");
    } catch (Exception e) {
        Log.e("HTTP", "Error in http connection " + e.toString());
    }

방금 확인했는데 당신과 같은 코드를 가지고 있고 완벽하게 작동합니다.유일한 차이점은 파라미터의 목록을 어떻게 작성하느냐는 다음과 같습니다.

사용하고 있다:ArrayList<BasicNameValuePair> params

이렇게 채웁니다.

 params.add(new BasicNameValuePair("apikey", apikey);

JSONObject를 사용하여 웹 서비스에 매개 변수를 전송하지 않습니다.

JSONObject를 사용해야 합니까?

퍼블릭 클래스 GetUsers가 비동기 태스크 확장 {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }

    public String connect()
    {
        HttpClient httpclient = new DefaultHttpClient();

        // Prepare a request object
        HttpPost htopost = new HttpPost("URL");
        htopost.setHeader(new BasicHeader("Authorization","Basic Og=="));

        try {

            JSONObject param = new JSONObject();
            param.put("PageSize",100);
            param.put("Userid",userId);
            param.put("CurrentPage",1);

            htopost.setEntity(new StringEntity(param.toString()));

            // Execute the request
            HttpResponse response;

            response = httpclient.execute(htopost);
            // Examine the response status
            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            if (entity != null) {

                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result = convertStreamToString(instream);

                // A Simple JSONObject Creation
                json = new JSONArray(result);

                // Closing the input stream will trigger connection release
                instream.close();
                return ""+response.getStatusLine().getStatusCode();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected String doInBackground(String... urls) {
        return connect();
    }

    @Override
    protected void onPostExecute(String status){
        try {

            if(status.equals("200"))
            {

                    Global.defaultMoemntLsit.clear();

                    for (int i = 0; i < json.length(); i++) {
                        JSONObject ojb = json.getJSONObject(i);
                        UserMomentModel u = new UserMomentModel();
                        u.setId(ojb.getString("Name"));
                        u.setUserId(ojb.getString("ID"));


                        Global.defaultMoemntLsit.add(u);
                    }




                            userAdapter = new UserAdapter(getActivity(), Global.defaultMoemntLsit);
                            recycleView.setAdapter(userMomentAdapter);
                            recycleView.setLayoutManager(mLayoutManager);
           }



        }
        catch (Exception e)
        {
            e.printStackTrace();

        }
    }
}

언급URL : https://stackoverflow.com/questions/6028981/using-httpclient-and-httppost-in-android-with-post-parameters

반응형