android - Android HTTP POST 问题

标签 android http post get

我正在使用以下代码执行 HTTP POST 请求。 PostData 为字符串形式

PostData 示例:

瓮:马林鱼:宽 乐队:1-1:注册 服务:li nk采集器: 马林鱼:组织 ionic :testpdc:devi ce-maker-x:client tnemo:aa08a1:59e a7e8cfa7a8582http://docs.oasi s-open.org/wss/2 004/01/绿洲-200 401-wss-wssecuri ty-utility-1.0.x sd"URI="urn:mar 林:核心:1.0:nem o:协议(protocol):profi le:1"wsu:Id="si gid0003"nemosec :用法="http://n 情绪.互信.c om/2005/10/安全 城市/个人资料"/>< /SOAP-ENV:信封 pe>

我们期待一个 xml/soap 响应,但我们得到的是一个 xml 文件作为响应。谁能告诉我执行 HTTP POST 的过程是否正确(如以下代码所示)

注意:使用 cuRL 执行 POST 时,相同的 postData 工作正常。

public byte [] sendRecv(String PostData, long postDataSize){

  try{
   if(!(PostData.equals("empty"))){
    isPost = true;
    //InputStream postDataInputStream = new ByteArrayInputStream(postData);
    //BasicHttpEntity httpPostEntity = new BasicHttpEntity();
    //httpPostEntity.setContent(postDataInputStream);
    StringEntity httpPostEntity = new StringEntity(PostData, HTTP.UTF_8);
    //httpPostEntity.setContentLength(postData.length);
    //httpPostEntity.setContentType("application/x-www-form-urlencoded");
    httpPost.setEntity(httpPostEntity);
    httpPost.setHeader("Content-Length", new Integer(PostData.length()).toString());
    httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    httpPost.setHeader("Expect", "100-continue");

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

  try {
   if(isPost == true){
    response = mAndroidHttpClient.execute(httpPost);
    isPost = false;
   }
   else {
    response = mAndroidHttpClient.execute(httpGet);
   }
   statusCode = response.getStatusLine().getStatusCode();

   if(statusCode != 200 ){
    if(statusCode == 404) {
     //System.out.println("error in http connection : 404");

     //return ERR_HTTP_NOTFOUND 
    } else if(statusCode == 500){
     //System.out.println("error in http connection : 500");
     //return ERR_HTTP_INTERNALSEVERERROR
    } else {
     //System.out.println("error in http connection : error unknown");
     //return ERR_HTTP_FATAL
    }
   }

   HttpEntity entity = response.getEntity();
   InputStream is = entity.getContent();

   ByteArrayOutputStream bos = new ByteArrayOutputStream();
   for (int next = is.read(); next != ENDOFSTREAM; next = is.read()) {
    bos.write(next);
   }
   responseBuffer = bos.toByteArray();
   bos.flush();
   bos.close();

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

   return responseBuffer;
 }  

最佳答案

这是我的实现,它适用于 post 和 get。您可以将设置与您的设置进行比较。

/**
 * Allows you to easily make URL requests
 * 
 * 
 * @author Jack Matthews
 * 
 */
class HttpUrlRequest extends Thread {

    private static final String TAG = "HttpUrlRequest";
    private static final HttpClient httpClient;



    static {
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpProtocolParams.setUseExpectContinue(params, false);  
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);
        ConnManagerParams.setMaxTotalConnections(params, 100);
        ConnManagerParams.setTimeout(params, 30000);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https",PlainSocketFactory.getSocketFactory(), 80));
        ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
        httpClient = new DefaultHttpClient(manager, params);
        //httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
    }


    //user supplied variables
    private String host = null;
    private int port = 80;
    private String path = null;
    private List<NameValuePair> query = null;
    private List<NameValuePair> post = null;
    private Handler handler = null;
    private HttpResponseWrapper callbackWrapper = null;
    private String scheme = "http";


    /**
     * Used to setup a request to a url
     * 
     * @param host
     * @param port
     * @param path
     * @param query
     * @param post
     * @param handler
     * @param callbackWrapper
     */
    private HttpUrlRequest(String scheme, String host, int port, String path, List<NameValuePair> query,  List<NameValuePair> post, Handler handler, HttpResponseWrapper callbackWrapper) {
        this.scheme = scheme;
        this.host = host;
        this.port = port;
        this.path = path;
        this.query = query;
        this.post = post;
        this.handler = handler;
        this.callbackWrapper = callbackWrapper;
    }




    /**
     * Use this class if your class is implementing HttpResponseListener.
     * Creates the request inside it's own Thread automatically.
     * <b>run() is called automatically</b>
     * 
     * @param host
     * @param port
     * @param path
     * @param queryString
     * @param postData
     * @param requestCode
     * @param callback
     * 
     * @see HttpResponseListener
     */
    public static void sendRequest(String scheme, String host, int port, String path, List<NameValuePair> queryString, List<NameValuePair> postData, int requestCode, HttpResponseListener callback) {
        (new HttpUrlRequest(scheme, host, port, path, queryString, postData, new Handler(),new HttpResponseWrapper(callback,requestCode))).start();
    }


    /**
     * Use this method if you want to control the Threading yourself.
     * 
     * @param host
     * @param port
     * @param path
     * @param queryString
     * @param postData
     * @return
     */
    public static HttpResponse sendRequestForImmediateResponse(String scheme,String host, int port, String path, List<NameValuePair> queryString, List<NameValuePair> postData) {
        HttpUrlRequest req = new HttpUrlRequest(scheme, host, port, path, queryString, postData, null, null);
        return req.runInCurrentThread();
    }



    /**
     * Runs the request in the current Thread, use this if you
     * want to mananage Threading yourself through a thread pool etc.
     * 
     * @return HttpResponse
     */
    private HttpResponse runInCurrentThread() {
        if(post==null) {
            return simpleGetRequest();
        } else {
            return simplePostRequest();
        }
    }




    @Override
    public void run() {
        //Determine the appropriate method to use
        if(post==null) {
            callbackWrapper.setResponse(simpleGetRequest());
            handler.post(callbackWrapper);
        } else {
            callbackWrapper.setResponse(simplePostRequest());
            handler.post(callbackWrapper);
        }
    }





    /**
     * Send a GET request
     * 
     * @return HttpResponse or null if an exception occurred
     * 
     */
    private HttpResponse simpleGetRequest() {
        try {
            //Add lang to query string
            query.add(new BasicNameValuePair("lang", getLanguageInJoomlaFormat()));
            URI uri = URIUtils.createURI(scheme, host, port, path, URLEncodedUtils.format(query, HTTP.UTF_8), null);

            if(Logging.DEBUG) Log.d(TAG, uri.toString());

            //GET method
            HttpGet method = new HttpGet(uri);
            HttpResponse response = httpClient.execute(method);
            //HttpEntity entity = response.getEntity();

            if(response==null)
                return NullHttpResponse.INSTANCE;
            else
                return response;

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

        return NullHttpResponse.INSTANCE;
    }





    /**
     * Send a POST request
     * 
     * 
     * @return HttpResponse or null if an exception occurred
     * 
     */
    private HttpResponse simplePostRequest() {
        try {
            //Add lang to query string
            query.add(new BasicNameValuePair("lang", getLanguageInJoomlaFormat() ));

            URI uri = URIUtils.createURI(scheme, host, port, path, URLEncodedUtils.format(query, HTTP.UTF_8), null);

            if(Logging.DEBUG) Log.d(TAG, uri.toString());

            //POST method
            HttpPost postMethod=new HttpPost(uri);      
            postMethod.setEntity(new UrlEncodedFormEntity(post, HTTP.UTF_8));
            HttpResponse response = httpClient.execute(postMethod);
            //HttpEntity entity = response.getEntity();

            if(response==null)
                return NullHttpResponse.INSTANCE;
            else
                return response;

        } catch (UnsupportedEncodingException e) {
            if(Logging.ERROR) Log.e(TAG, "UnsupportedEncodingException", e);
        } catch (ClientProtocolException e) {
            if(Logging.ERROR) Log.e(TAG, "UnsupportedEncodingException", e);
        } catch (IOException e) {
            if(Logging.ERROR) Log.e(TAG, "UnsupportedEncodingException", e);
        } catch (URISyntaxException e) {
            if(Logging.ERROR) Log.e(TAG, "UnsupportedEncodingException", e);
        }

        return NullHttpResponse.INSTANCE;
    }




    /**
     * Converts the language code to correct Joomla format
     * 
     * @return language in the (en-GB)
     */
    public static String getLanguageInJoomlaFormat() {
        String joomlaName;
        String[] tokens = Locale.getDefault().toString().split("_");
        if (tokens.length >= 2 && tokens[1].length() == 2) {
            joomlaName = tokens[0]+"-"+tokens[1];
        } else {
            joomlaName = tokens[0]+"-"+tokens[0].toUpperCase();
        }
        return joomlaName;
    }





    /**
     * Creates a null http response
     * 
     * @author Jack Matthews
     *
     */
    private enum NullHttpResponse implements HttpResponse {
        INSTANCE;

        @Override
        public HttpEntity getEntity() {
            return null;
        }

        @Override
        public Locale getLocale() {
            return null;
        }

        @Override
        public StatusLine getStatusLine() {
            return null;
        }

        @Override
        public void setEntity(HttpEntity entity) {

        }

        @Override
        public void setLocale(Locale loc) {

        }

        @Override
        public void setReasonPhrase(String reason) throws IllegalStateException {

        }

        @Override
        public void setStatusCode(int code) throws IllegalStateException {

        }

        @Override
        public void setStatusLine(StatusLine statusline) {

        }

        @Override
        public void setStatusLine(ProtocolVersion ver, int code) {

        }

        @Override
        public void setStatusLine(ProtocolVersion ver, int code, String reason) {

        }

        @Override
        public void addHeader(Header header) {

        }

        @Override
        public void addHeader(String name, String value) {

        }

        @Override
        public boolean containsHeader(String name) {
            return false;
        }

        @Override
        public Header[] getAllHeaders() {
            return null;
        }

        @Override
        public Header getFirstHeader(String name) {
            return null;
        }

        @Override
        public Header[] getHeaders(String name) {
            return null;
        }

        @Override
        public Header getLastHeader(String name) {
            return null;
        }

        @Override
        public HttpParams getParams() {
            return null;
        }

        @Override
        public ProtocolVersion getProtocolVersion() {
            return null;
        }

        @Override
        public HeaderIterator headerIterator() {
            return null;
        }

        @Override
        public HeaderIterator headerIterator(String name) {
            return null;
        }

        @Override
        public void removeHeader(Header header) {

        }

        @Override
        public void removeHeaders(String name) {

        }

        @Override
        public void setHeader(Header header) {

        }

        @Override
        public void setHeader(String name, String value) {

        }

        @Override
        public void setHeaders(Header[] headers) {

        }

        @Override
        public void setParams(HttpParams params) {

        }
    }

}

关于android - Android HTTP POST 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4277077/

相关文章:

android - phonegap android ajax 请求适用于 GET 但不适用于 POST

java - 尝试从 Android 数据库中获取数据时 JSON 显示错误 403

java - 如何通过 java httpClient 查找目标 Web 服务器的任何信息?

http - 基本接入认证安全吗?

c++ - Boost.Beast 高级服务器示例中的 HTTP 管道与 WebSocket

java - 对于 Wildfly 中以 .html 文件结尾的 URL,此 URL 不支持 HTTP 方法 POST

python - 发送 POST 请求的正文

android - 在相对布局中创建布局

Android更改按钮背景没有按下状态的选择器

android - 与 Firebase 混淆变量范围