Android项目使用httpclient – > http.client(apache),post / get方法
我正在做一个Android项目的获取和发布的方法,我需要“翻译”HttpClient的3.x到HttpClient的4.x(由Android使用)。 我的问题是,我不知道我做了什么,我没有find一些方法的“翻译”…
这是我做的HttpClient 3.x和( – >)HttpClient 4.x“翻译”,如果我find了它(只有党派问我问题):
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(...,...); --> ?
我不知道这是否正确。 这已经引起了问题,因为软件包没有被类似命名,也有一些方法。 我只是需要文件(我没有find)和一点帮助。
预先感谢您的帮助。 迈克尔
这里是HttpClient 4文档 ,这是Android使用的(4,而不是3,从1.0-> 2.x)。 文档很难find(谢谢Apache;)),因为HttpClient现在是HttpComponents的一部分(如果你只是寻找HttpClient,你通常会在3.x的东西)。
另外,如果你做了任何数量的请求,你不想一遍又一遍地创build客户端。 相反,作为HttpClient的教程注意 ,创build客户端一次,并保持在周围。 从那里使用ThreadSafeConnectionManager 。
我使用一个辅助类,例如像HttpHelper (这仍然是一个移动的目标 – 我打算把它移到它自己的Android实用项目在某个时刻,并支持二进制数据,还没有得到那里),以帮助这个。 帮助程序类创build客户端,并具有get / post / etc的便捷包装方法。 在Activity中使用这个类的地方,你应该创build一个内部的AsyncTask (这样你就不会在发出请求时阻塞UI Thread),例如:
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); } } }
回答我的问题的最简单的方法是向你展示我所做的课程:
公共类HTTPHelp { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); 私人布尔中止; 私人stringret; HttpResponse response = null; HttpPost httpPost = null; public HTTPHelp(){ } public void clearCookies(){ httpClient.getCookieStore()清除()。 } public void abort(){ 尝试{ 如果(HttpClient的!= NULL){ 的System.out.println( “取消”); 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,”+ “应用程序/ XHTML + xml的,text / html的; Q = 0.9,文本/无格式; Q = 0.8,图像/ PNG,* / *; Q = 0.5”); httpPost.setHeader(“Content-Type”,“application / x-www-form-urlencoded”); 尝试{ tmp = new StringEntity(data,“UTF-8”); catch(UnsupportedEncodingException e){ System.out.println(“HTTPHelp:UnsupportedEncodingException:”+ e); } httpPost.setEntity(TMP); 尝试{ 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(); 返回 } }
我用这个教程来做我的post方法和例子 (谢谢丹尼尔)。
感谢您的帮助。
那么你可以在这里find那个版本的HTTPClient
文档。 通过他们提供的示例场景特别有用。
不幸的是,我不知道HTTPClient
所以我不能给予直接的等价。 我build议你采取你想要做的,并通过他们的示例场景。
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)); } }