Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android HTTP POST的问题_Android_Http_Post_Get - Fatal编程技术网

Android HTTP POST的问题

Android HTTP POST的问题,android,http,post,get,Android,Http,Post,Get,我正在使用下面的代码执行HTTP POST请求。PostData是字符串形式的 PostData示例: 瓮:马林鱼:宽 波段:1-1:寄存器 预约服务:李 nkAcquisitionurn: 马林:组织 离子:testpdc:devi ce-maker-x:clien tnemo:aa08a1:59e a7e8cfa7a8582http://docs.oasi s-open.org/wss/2 004/01/oasis-200 401 wss wssecuri ty-utility-1.0.x

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

PostData示例:

瓮:马林鱼:宽 波段:1-1:寄存器 预约服务:李 nkAcquisitionurn: 马林:组织 离子:testpdc:devi ce-maker-x:clien tnemo:aa08a1:59e a7e8cfa7a8582http://docs.oasi s-open.org/wss/2 004/01/oasis-200 401 wss wssecuri ty-utility-1.0.x sd“URI=”urn:mar 林:核心:1.0:nem o:协议:profi le:1“wsu:Id=“si gid0003“nemosec :Usage=“http://n emo.intertrust.c om/2005/10/secur 城市/个人资料“/>< /SOAP-ENV:Envelo pe>

我们希望得到一个xml/soap响应,而不是一个xml文件作为响应

注意:当与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) {

        }
    }

}
/**
*允许您轻松地发出URL请求
* 
* 
*@作家杰克·马修斯
* 
*/
类HttpUrlRequest扩展线程{
私有静态最终字符串标记=“HttpUrlRequest”;
私有静态最终HttpClient HttpClient;
静止的{
HttpParams params=新的BasicHttpParams();
HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params,HTTP.UTF_8);
HttpProtocolParams.setUseExpectContinue(params,false);
HttpConnectionParams.setConnectionTimeout(参数,10000);
HttpConnectionParams.setSoTimeout(参数,10000);
ConnManagerParams.setMaxTotalConnections(参数,100);
ConnManagerParams.setTimeout(参数,30000);
SchemeRegistry registry=新SchemeRegistry();
register(新方案(“http”,PlainSocketFactory.getSocketFactory(),80));
register(新方案(“https”,PlainSocketFactory.getSocketFactory(),80));
ThreadSafeClientConnManager=新的ThreadSafeClientConnManager(参数,注册表);
httpClient=新的默认httpClient(管理器,参数);
//httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_超时,30000);
}
//用户提供的变量
私有字符串主机=null;
专用int端口=80;
私有字符串路径=null;
私有列表查询=null;
私有列表post=null;
私有处理程序=null;
私有HttpResponseWrapper callbackWrapper=null;
私有字符串scheme=“http”;
/**
*用于设置对url的请求
* 
*@param主机
*@param端口
*@param路径
*@param查询
*@param post
*@param处理程序
*@param callbackWrapper
*/
私有HttpUrlRequest(字符串方案、字符串主机、int端口、字符串路径、列表查询、列表post、处理程序处理程序、HttpResponseWrapper callbackWrapper){
this.scheme=scheme;
this.host=host;
this.port=端口;
this.path=path;
this.query=query;
this.post=post;
this.handler=handler;
this.callbackWrapper=callbackWrapper;
}
/**
*如果您的类正在实现HttpResponseListener,请使用该类。
*在自己的线程内自动创建请求。
*run()是自动调用的
* 
*@param主机
*@param端口
*@param路径
*@param查询字符串
*@param postData
*@param请求代码
*@param回调
* 
*@见HttpResponseListener
*/
公共静态void sendRequest(字符串方案、字符串主机、int端口、字符串路径、列表queryString、列表postData、int requestCode、HttpResponseListener回调){
(新的HttpUrlRequest(方案、主机、端口、路径、查询字符串、postData、新处理程序()、新的HttpResponseWrapper(回调、请求代码))).start();
}
/**
*如果要自己控制线程,请使用此方法。
* 
*@param主机
*@param端口
*@param路径
*@param查询字符串
*@param postData
*@返回
*/
公共静态HttpResponse sendRequestForImmediateResponse(字符串方案、字符串主机、int端口、字符串路径、列表查询字符串、列表postData){
HttpUrlRequest req=新的HttpUrlRequest(方案、主机、端口、路径、查询字符串、postData、null、null);
返回req.RUNIRRENTTHREAD();
}
/**
*在当前线程中运行请求,如果
*希望通过线程池等管理线程。
* 
*@return-HttpResponse
*/
私有HttpResponse runInirentThread(){
if(post==null){
返回simpleGetRequest();
}否则{
返回simplePostRequest();
}
}
@凌驾
公开募捐{
//确定要使用的适当方法
if(post==null){
setResponse(simpleGetRequest());
handler.post(callbackWrapper);
}否则{
setResponse(simplePostRequest());
handler.post(callbackWrapper);
}
}
/**
*发送GET请求
* 
*@如果发生异常,返回HttpResponse或null
* 
*/
私有HttpResponse simpleGetRequest(){
试一试{
//将lang添加到查询字符串
add(新的BasicNameValuePair(“lang”,getLanguageInJoomlaFormat());
uriuri=URIUtils.createURI(scheme、host、port、path、URLEncodedUtils.format(query,HTTP.UTF_8),null);
if(Logging.DEBUG)Log.d(标记,uri.toString());
//获取方法
HttpGet方法=新的HttpGet(uri);
HttpResponse response=httpClient.execute(方法);
//HttpEntity=response.getEntity();
如果(响应==null)
返回NullHttpResponse.INSTANCE;
其他的
返回响应;
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
          DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
         dbfac.setNamespaceAware(true);
         DocumentBuilder docBuilder = null;
         try {
            docBuilder = dbfac.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         DOMImplementation domImpl = docBuilder.getDOMImplementation();
         Document doc = domImpl.createDocument("http://coggl.com/InsertTrack","TrackEntry", null);
         doc.setXmlVersion("1.0");
         doc.setXmlStandalone(true);

         Element trackElement = doc.getDocumentElement();

         Element CompanyId = doc.createElement("CompanyId");
         CompanyId.appendChild(doc.createTextNode("1"));
         trackElement.appendChild(CompanyId);

         Element CreatedBy = doc.createElement("CreatedBy");
         CreatedBy.appendChild(doc.createTextNode("6"));
         trackElement.appendChild(CreatedBy);

         Element DepartmentId = doc.createElement("DepartmentId");
         DepartmentId.appendChild(doc.createTextNode("4"));
         trackElement.appendChild(DepartmentId);

         Element IsBillable = doc.createElement("IsBillable");
         IsBillable.appendChild(doc.createTextNode("1"));
         trackElement.appendChild(IsBillable);

         Element ProjectId = doc.createElement("ProjectId");
         ProjectId.appendChild(doc.createTextNode("1"));
         trackElement.appendChild(ProjectId);

         Element StartTime = doc.createElement("StartTime");
         StartTime.appendChild(doc.createTextNode("2012-03-14 10:44:45"));
         trackElement.appendChild(StartTime);

         Element StopTime = doc.createElement("StopTime");
         StopTime.appendChild(doc.createTextNode("2012-03-14 11:44:45"));
         trackElement.appendChild(StopTime);

         Element TaskId = doc.createElement("TaskId");
         TaskId.appendChild(doc.createTextNode("3"));
         trackElement.appendChild(TaskId);

         Element TotalTime = doc.createElement("TotalTime");
         TotalTime.appendChild(doc.createTextNode("1"));
         trackElement.appendChild(TotalTime);

         Element TrackDesc = doc.createElement("TrackDesc");
         TrackDesc.appendChild(doc.createTextNode("dello testing"));
         trackElement.appendChild(TrackDesc);

         Element TrackId = doc.createElement("TrackId");
         TrackId.appendChild(doc.createTextNode("0"));
         trackElement.appendChild(TrackId);

         TransformerFactory transfac = TransformerFactory.newInstance();
         Transformer trans = null;
        try {
            trans = transfac.newTransformer();
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
         trans.setOutputProperty(OutputKeys.INDENT, "yes");

         //create string from xml tree
         StringWriter sw = new StringWriter();
         StreamResult result = new StreamResult(sw);
         DOMSource source = new DOMSource(doc);
         try {
            trans.transform(source, result);
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         String xmlString = sw.toString();
         DefaultHttpClient httpClient = new DefaultHttpClient();

         HttpPost httppost = new HttpPost("http://192.168.0.19:3334/cogglrestservice.svc/InsertTrack");     
         // Make sure the server knows what kind of a response we will accept
         httppost.addHeader("Accept", "text/xml");
         // Also be sure to tell the server what kind of content we are sending
         httppost.addHeader("Content-Type", "application/xml");

         try
         {
         StringEntity entity = new StringEntity(xmlString, "UTF-8");
         entity.setContentType("application/xml");
         httppost.setEntity(entity);

         // execute is a blocking call, it's best to call this code in a thread separate from the ui's
         HttpResponse response = httpClient.execute(httppost);

         BasicResponseHandler responseHandler = new BasicResponseHandler();
            String strResponse = null;
            if (response != null) {
                try {
                    strResponse = responseHandler.handleResponse(response);
                } catch (HttpResponseException e) {
                    e.printStackTrace();  
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Log.e("WCFTEST", "WCFTEST ********** Response" + strResponse);    


         }
         catch (Exception ex)
         {
         ex.printStackTrace();
         }
         Toast.makeText(EditTask.this, "Xml posted succesfully.",Toast.LENGTH_SHORT).show();