문제

Android 프로젝트를위한 Get and Post 메소드를 수행하고 있으며 httpclient 3.x를 httpclient 4.x (Android 사용)로 "번역"해야합니다. 내 문제는 내가 한 일을 확신하지 못하고 일부 방법의 "번역"을 찾지 못한다는 것입니다 ...

이것은 내가 한 httpclient 3.x이며 (->) httpclient 4.x "번역"을 찾은 경우 (문제를 묻는 당사자 만) :

HttpState state = new HttpState (); --> ?

HttpMethod method = null; --> HttpUriRequest httpUri = null;

method.abort(); --> httpUri.abort(); //httpUri is a HttpUriRequest

method.releaseConnection(); --> conn.disconnect(); //conn is a HttpURLConnection

state.clearCookies(); --> cookieStore.clear(); //cookieStore is a BasicCookieStore

HttpClient client = new HttpClient(); --> DefaultHttpClient client = new DefaultHttpClient();

client.getHttpConnectionManager().getParams().setConnectionTimeout(SOCKET_TIMEOUT) --> HttpConnectionParams.setConnectionTimeout(param, SOCKET_TIMEOUT);

client.setState(state); --> ?

client.getParams().setCookiePolicy(CookiePolicy.RFC_2109); --> HttpClientParams.setCookiePolicy(param, CookiePolicy.RFC_2109);

PostMethod post = (PostMethod) method; --> ?

post.setRequestHeader(...,...); --> conn.setRequestProperty(...,...);

post.setFollowRedirects(false); --> conn.setFollowRedirects(false);

RequestEntity tmp = null; --> ?

tmp = new StringRequestEntity(...,...,...); --> ?

int statusCode = client.executeMethod(post); --> ?

String ret = method.getResponsBodyAsString(); --> ?

Header locationHeader = method.getResponseHeader(...); --> ?

ret = getPage(...,...); --> ?

그것이 맞는지 모르겠습니다. 패키지가 비슷하게 명명되지 않았고 일부 방법도 문제가 발생했습니다. 문서 (찾지 못했음)와 도움이 필요합니다.

도움이 되었습니까?

해결책 2

내 질문에 대답하는 가장 쉬운 방법은 내가 만든 수업을 보여주는 것입니다.

public class HTTPHelp{

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    private boolean abort;
    private String ret;

    HttpResponse response = null;
    HttpPost httpPost = null;

    public HTTPHelp(){

    }

    public void clearCookies() {

        httpClient.getCookieStore().clear();

    }

    public void abort() {

        try {
            if(httpClient!=null){
                System.out.println("Abort.");
                httpPost.abort();
                abort = true;
            }
        } catch (Exception e) {
            System.out.println("HTTPHelp : Abort Exception : "+e);
        }
    }

    public String postPage(String url, String data, boolean returnAddr) {

        ret = null;

        httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);

        httpPost = new HttpPost(url);
        response = null;

        StringEntity tmp = null;        

        httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux " +
            "i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
        httpPost.setHeader("Accept", "text/html,application/xml," +
            "application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

        try {
            tmp = new StringEntity(data,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);
        }

        httpPost.setEntity(tmp);

        try {
            response = httpClient.execute(httpPost,localContext);
        } catch (ClientProtocolException e) {
            System.out.println("HTTPHelp : ClientProtocolException : "+e);
        } catch (IOException e) {
            System.out.println("HTTPHelp : IOException : "+e);
        } 
                ret = response.getStatusLine().toString();

                return ret;
                }
}

나는 사용했다 이 튜토리얼 내 게시물 방법을 수행합니다 예제

다른 팁

여기에 있습니다 httpclient 4 문서, 이것이 바로 Android가 사용하는 것입니다 (1.0-> 2.x 기준으로 3, 3이 아닌 4). httpclient가 이제 httpcomponents의 일부이기 때문에 문서는 찾기가 어렵습니다 (Apache;).

또한 여러 요청이 있으면 클라이언트를 반복해서 만들고 싶지 않습니다. 오히려 httpclient note에 대한 튜토리얼, 한 번 클라이언트를 만들고 주위에 보관하십시오. 거기에서 사용하십시오 ThreadSafeConnectionManager.

예를 들어 도우미 클래스를 사용합니다. httphelper (여전히 움직이는 목표 - 나는 이것을 어느 시점에서 자체 Android Util 프로젝트로 옮길 계획이며, 이진 데이터를 아직 지원하지 않았습니다). 도우미 클래스는 클라이언트를 생성하고 Get/Post/etc를위한 편의 래퍼 방법을 가지고 있습니다. 이 클래스를 사용하는 모든 곳 활동, 내부 내부를 만들어야합니다 Asynctask (요청을 작성하는 동안 UI 스레드를 차단하지 않도록) : 예를 들어 :

    private class GetBookDataTask extends AsyncTask<String, Void, Void> {
      private ProgressDialog dialog = new ProgressDialog(BookScanResult.this);

      private String response;
      private HttpHelper httpHelper = new HttpHelper();

      // can use UI thread here
      protected void onPreExecute() {
         dialog.setMessage("Retrieving HTTP data..");
         dialog.show();
      }

      // automatically done on worker thread (separate from UI thread)
      protected Void doInBackground(String... urls) {
         response = httpHelper.performGet(urls[0]);
         // use the response here if need be, parse XML or JSON, etc
         return null;
      }

      // can use UI thread here
      protected void onPostExecute(Void unused) {
         dialog.dismiss();
         if (response != null) {
            // use the response back on the UI thread here
            outputTextView.setText(response);
         }
      }
   }

글쎄, 당신은 해당 버전에서 문서를 찾을 수 있습니다. HTTPClient 여기; 특히 유용합니다 예제 시나리오 그들은 참석합니다.

불행히도 버전 3의 버전을 모릅니다 HTTPClient 그래서 나는 직접적인 동등성을 줄 수 없습니다. 나는 당신이하려는 일을 취하고 그들의 예제 시나리오를 살펴 보는 것이 좋습니다.

    package com.service.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class WebServiceDemoActivity extends Activity 
{
    /** Called when the activity is first created. */
    private static String SOAP_ACTION1 = "http://tempuri.org/GetSubscriptionReportNames";//"http://tempuri.org/FahrenheitToCelsius";
    private static String NAMESPACE = "http://tempuri.org/";
    private static String METHOD_NAME1 = "GetSubscriptionReportNames";//"FahrenheitToCelsius";
    private static String URL = "http://icontrolusa.com:8040/iPhoneService.asmx?WSDL";

    Button btnFar,btnCel,btnClear;
    EditText txtFar,txtCel;
    ArrayList<String> headlist = new ArrayList<String>();
    ArrayList<String> reportlist = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnFar = (Button)findViewById(R.id.btnFar);
        btnCel = (Button)findViewById(R.id.btnCel);
        btnClear = (Button)findViewById(R.id.btnClear);
        txtFar = (EditText)findViewById(R.id.txtFar);
        txtCel = (EditText)findViewById(R.id.txtCel);

        btnFar.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View v) 
            {
                //Initialize soap request + add parameters
                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);        

                //Use this to add parameters
                request.addProperty("Fahrenheit",txtFar.getText().toString());

                //Declare the version of the SOAP request
                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

                envelope.setOutputSoapObject(request);
                envelope.dotNet = true;

                try {
                    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                    //this is the actual part that will call the webservice
                    androidHttpTransport.call(SOAP_ACTION1, envelope);

                    // Get the SoapResult from the envelope body.
                    SoapObject result = (SoapObject)envelope.bodyIn;

                    if(result != null)
                    {
                        //Get the first property and change the label text
                        txtCel.setText(result.getProperty(0).toString());
                        Log.e("err  ","output is ::::   "+result.getProperty(0).toString());

                        parseSON();
                    }
                    else
                    {
                        Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        btnClear.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) 
            {
                txtCel.setText("");
                txtFar.setText("");
            }
        });
    }

    private void parseSON() {
            headlist.clear();
            reportlist.clear();
            String text = txtCel.getText().toString() ;//sb.toString();
            Log.i("######", "###### "+text);

            try{
                JSONObject jobj = new JSONObject(text);   
                JSONArray  jarr = jobj.getJSONArray("Head");
                for(int i=0;i<jarr.length();i++){
                    JSONObject e = jarr.getJSONObject(i);
                    JSONArray names = e.names();
                    for(int j=0;j<names.length();j++){
                        String tagname = names.getString(j);
                        if (tagname.equals("ReportID")) {
                            headlist.add(e.getString("ReportID"));
                        }
                        if (tagname.equals("ReportName")) {
                            reportlist.add(e.getString("ReportName"));
                        }
                    }
                }    
            } catch(JSONException e){
                Log.e("retail_home", "Error parsing data "+e.toString());
            }

            Log.d("length ", "head lenght "+headlist.size());
            Log.d("value is  ", "frst "+headlist.get(0));
            Log.d("length ", "name lenght "+reportlist.size());
            Log.d("value is  ", "secnd "+reportlist.get(0));

    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top