HttpClient不起作用

时间:2015-12-27 07:27:34

标签: android android-studio apache-httpclient-4.x

由于HttpClient在API级别22中已弃用,在API级别23中已删除,因此我使用了

android {
    useLibrary 'org.apache.http.legacy'
}

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'` 

根据以下链接:Lik1Link 2 。我使用下面的类来连接和读取服务器中的信息:

public class Webservice {

public static String readurl(String url, ArrayList<NameValuePair> params) {

    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost method = new HttpPost(url);
        if (params != null) {
            method.setEntity(new UrlEncodedFormEntity(params));

        }
        HttpResponse response = client.execute(method);
        InputStream stream = response.getEntity().getContent();
        String result = inputstreamTOString(stream);
        return result;
    }
    catch (ClientProtocolException e) {

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

        e.printStackTrace();
    }

    return null;
}
}

但是当我运行我的应用时,它已在String result = Webservice.readurl(url, params);中崩溃 在鳕鱼下面:

public void populateFromServer() {

    String url = G.server_service;
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("action", "read"));
    String result = Webservice.readurl(url, params);

.
.
.
}

1 个答案:

答案 0 :(得分:0)

因为您没有指定错误到底是什么。我将为您提供一个漂亮的HttpTask代码,它与JSONParser配合使用。

如果您的中间件以JSON响应,此代码将起作用。

调用HTTPTask

Boolean Some_variable = new HttpTask(getBaseContext()).doInBackground("test");

<强> HttpTask

package com.example.summer.toothbrush;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

public class HttpTask extends AsyncTask<String,Void,Boolean> {

    Context mainContext;
    JSONObject jsonObject;

    public HttpTask(Context context){ mainContext = context;  }

    @Override
    protected Boolean doInBackground(String... params){
    jsonObject = new JSONObject();
    JSONObject responseJsonObject = new JSONObject();
    StringBuilder result = new StringBuilder("");
    JSONParser jsonParser = new JSONParser(mainContext);
    if(params[0] == "test")
        jsonObject.put("test", "test");

    try{
        responseJsonObject = jsonParser.passJSONinURL(jsonObject,params[0]);
        result.append(responseJsonObject.get("status").toString());
        Log.d("Result", result.toString());
    }
    catch(JSONException e){
        e.printStackTrace();
    }
    if(result.toString().equals("true"))
        return true;
    else
        return false;
    }
}

<强> JSONParser

package com.example.summer.toothbrush;

import android.content.Context;
import android.os.StrictMode;
import android.util.Log;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;

public class JSONParser {

Context mainContext;
HttpResponse response;
StringBuilder result = new StringBuilder("");

public JSONParser(Context context){
    mainContext = context;
}

public JSONObject passJSONinURL(JSONObject obj,String mode){
    StringBuilder builder = new StringBuilder("");
    JSONObject jsonObject = new JSONObject();

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    try{
        response = null;
        HttpClient httpClient = new DefaultHttpClient();
        StringBuilder stringURL = new StringBuilder("");
        stringURL.append("http://100.100.10.10:8000/");
        if(mode.equals("test"))
            stringURL.append("test");

        //URLEncoder.encode() is used to encode the parameters in a request.
        stringURL.append(URLEncoder.encode(obj.toString(),"UTF-8"));
        //Toast.makeText(mainContext, stringURL.toString(),Toast.LENGTH_LONG).show();
        Log.d("JSON to be sent",stringURL.toString());
        HttpGet get = new HttpGet(stringURL.toString());
        response = httpClient.execute(get);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if(statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            reader.close();
        }
        else{
            Toast.makeText(mainContext,"Status Code Error!!!",Toast.LENGTH_LONG).show();
        }

    }
    catch(ClientProtocolException e){
        e.printStackTrace();
    }
    catch(IOException e){
        e.printStackTrace();
    }

    try{
        jsonObject = new JSONObject(builder.toString());

    }catch(JSONException e){
        Toast.makeText(mainContext,"JSON Parsing ERROR!!!!",Toast.LENGTH_LONG).show();
    }
    Log.d("JSONOBJECT : ",jsonObject.toString());
    return jsonObject;
}
}