AndroidプロジェクトのGetand Postメソッドを実行していて、HttpClient3.xをHttpClient4.xに「変換」する必要があります(Androidで使用)。私の問題は、 m何をしたのかわからず、いくつかのメソッドの「翻訳」が見つかりません。
これは私が行ったHttpClient3.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(...,...); --> ?
それが正しいかどうかはわかりません。これにより、パッケージの名前が同じではなく、一部のメソッドにも名前が付けられていないため、問題が発生しました。私はただドキュメント(私は見つけていません)と少しの助けが必要です。
私の質問に答える最も簡単な方法は、私が作成したクラスを表示することです。
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 docs 、つまりAndroidが使用しているものです(1.0-> 2.xの時点で3ではなく4)。ドキュメントは難しいfind(Apacheに感謝;))HttpClientはHttpComponentsの一部になっているため(そしてHttpClientを探すだけでは、通常は3.xのものになります)。
また、リクエストをいくつでも実行する場合は、クライアントを何度も作成したくありません。むしろ、 HttpClientノートのチュートリアル のように、クライアントを1回作成し、それを維持します。そこから 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);
}
}
}
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));
}
}