Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.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
java在维护Cookie的同时发送GET/POST请求_Java - Fatal编程技术网

java在维护Cookie的同时发送GET/POST请求

java在维护Cookie的同时发送GET/POST请求,java,Java,我使用的是ApacheHttpClient 4.2.5,我试图发送GET/POST请求,同时将cookies从一个请求传递到另一个请求(就像真正的浏览器一样) 有什么类似于PHP的cURL功能吗?cURL简单明了,但在谷歌上很难找到一段代码,它可以满足我在Java中的需求 我想要的很简单。让我发邮件,收到请求。同时,传递cookies,让我设置自己的标题。Java中是否有类似的功能?HttpClient只要使用相同的DefaultHttpClient对象 有什么类似于PHP的cURL功能吗?cU

我使用的是ApacheHttpClient 4.2.5,我试图发送GET/POST请求,同时将cookies从一个请求传递到另一个请求(就像真正的浏览器一样)

有什么类似于PHP的cURL功能吗?cURL简单明了,但在谷歌上很难找到一段代码,它可以满足我在Java中的需求

我想要的很简单。让我发邮件,收到请求。同时,传递cookies,让我设置自己的标题。Java中是否有类似的功能?

HttpClient
只要使用相同的
DefaultHttpClient
对象

有什么类似于PHP的cURL功能吗?cURL简单明了,但很难在谷歌上找到一段代码来满足我在Java中的需求

来自
Curl
world的东西:

curl -b -L -i  -X POST   
-d 'id=105'  
-d 'json={"orderBy":0,"categoryRelevant":false'}  \ http://env-findwifi.wifi.com/lClient/
**评论:

-b :: enable cookies (by default its disabled)
-L :: activate redirect
-i :: show output
但如果你真的想玩Java,这里有一些代码片段:

List<Cookie> mCookies = null;

...

public void redirect(String url){

    StringBuilder buff = new StringBuilder();

    DefaultHttpClient httpclient = null;
    //      boolean success = false;

    try {           
        Log.d("test_runner","send Data started");


        HttpParams params = new BasicHttpParams();
        int m_timeout = 60000;
        ConnManagerParams.setTimeout(params, m_timeout);            
        HttpConnectionParams.setStaleCheckingEnabled(params, false);
        HttpConnectionParams.setSocketBufferSize(params, 8192);

        HttpConnectionParams.setConnectionTimeout(params, m_timeout);    // connection timeout
        HttpConnectionParams.setSoTimeout(params, m_timeout);            // socket timeout

        HttpClientParams.setRedirecting(params, false);


        httpclient = new DefaultHttpClient(params);


        Log.d("test_runner", "URL: " + url);

        HttpGet httpget = new HttpGet(url);




        HttpContext context = new BasicHttpContext(); 
        HttpResponse response = httpclient.execute(httpget, context);



        //HttpResponse response = httpclient.execute(httpget);

        mCookies = httpclient.getCookieStore().getCookies();

        if (mCookies.isEmpty()) {
            Log.d("test_runner", "Cookies: None");
        } else {
            for (int i = 0; i < mCookies.size(); i++) {
                System.out.println("- " + mCookies.get(i).toString());
                Log.d("test_runner", "Cookies: [" + i + "]" + mCookies.get(i).toString());
            }
        }

        int statusCode =  response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            Header[] headers = response.getHeaders("Location");

            if (headers != null && headers.length != 0) {
                String newUrl =  headers[headers.length - 1].getValue();

                redirect(newUrl);                   

            } 
        }   
        else{ // status 200

            HttpHost currentHost = (HttpHost)  context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            mHost = currentHost.toURI();

            HttpEntity entity = response.getEntity();

            if (entity != null) {


                InputStream is = entity.getContent();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr, 1024 * 4);
                String line = null;
                while ( (line = br.readLine()) != null) {
                    //System.out.println("Data Sender: " +  line);

                    buff.append(line).append("\n");

                }
                is.close();

            } else {
                Log.d("test_runner", "Data Sender: response is null");
            }

            Log.d("test_runner", "Output: " +  buff);

            // do something


        }
    } catch (Exception e) {
        Log.e("test_runner", ThrowableToString.fromThrowableToString(e));
    }

    if (httpclient != null) {           
        httpclient.getConnectionManager().shutdown();
    }       

}
List mCookies=null;
...
公共无效重定向(字符串url){
StringBuilder buff=新的StringBuilder();
DefaultHttpClient httpclient=null;
//布尔成功=假;
试试{
Log.d(“test_runner”,“发送数据已启动”);
HttpParams params=新的BasicHttpParams();
int m_超时=60000;
setTimeout(参数,m_timeout);
HttpConnectionParams.SetStaleCheckEnabled(参数,false);
HttpConnectionParams.setSocketBufferSize(参数,8192);
HttpConnectionParams.setConnectionTimeout(params,m_timeout);//连接超时
HttpConnectionParams.setSoTimeout(参数,m_超时);//套接字超时
HttpClientParams.setRedirecting(参数,false);
httpclient=新的默认httpclient(参数);
Log.d(“测试运行者”,“URL:+URL”);
HttpGet HttpGet=新的HttpGet(url);
HttpContext=新的BasicHttpContext();
HttpResponse response=httpclient.execute(httpget,context);
//HttpResponse response=httpclient.execute(httpget);
mCookies=httpclient.getCookieStore().getCookies();
if(mCookies.isEmpty()){
Log.d(“测试运行者”,“Cookies:无”);
}否则{
对于(int i=0;i
在您可以将cookies用于post后:

    private void doPost(String formAction, String inputRootValue,
        String inputRootName, String onSubmitName, String onSubmitVal) {

    StringBuilder buff = new StringBuilder();

    DefaultHttpClient httpclient = null;

    try {  

    HttpParams params = new BasicHttpParams();
    int m_timeout = 60000;
    ConnManagerParams.setTimeout(params, m_timeout);            
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setSocketBufferSize(params, 8192);



    HttpClientParams.setRedirecting(params, false);


     CookieStore cookieStore = new BasicCookieStore(); 



     for(Cookie cook : mCookies){
         cookieStore.addCookie(cook); 
     }

     httpclient = new DefaultHttpClient(params);
     httpclient.setCookieStore(cookieStore);

     if(mHost != null){
         formAction =  mHost + "/www/" + formAction; 
     }
     else{
         formAction =  "http://localhost/www/" + formAction; 
     }




    HttpPost httpost = new HttpPost(formAction);

    List <NameValuePair> nvps = new ArrayList <NameValuePair>();
    nvps.add(new BasicNameValuePair(inputRootName, inputRootValue));
    nvps.add(new BasicNameValuePair(onSubmitName, onSubmitVal));


    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));




    HttpResponse response = httpclient.execute(httpost);

    HttpEntity entity = response.getEntity();

    if (entity != null) {

        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if(statusCode != 200){

        }

        Log.d("test_runner", "response.getStatusLine: " + response.getStatusLine());

        InputStream is = entity.getContent();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ( (line = br.readLine()) != null) {
            //System.out.println("Data Sender: " +  line);

            buff.append(line).append("\n");


        }
        is.close();

        //entity.consumeContent();
    } else {

    }

    Log.d("test_runner", "response: " + buff.toString());



} catch (Exception e) {
    Log.e("test_runner", ThrowableToString.fromThrowableToString(e));
}

if (httpclient != null) {
    // resource cleanup
    httpclient.getConnectionManager().shutdown();
}


}
private void doPost(字符串形式、字符串输入值、,
字符串inputRootName、字符串onSubmitName、字符串onSubmitVal){
StringBuilder buff=新的StringBuilder();
DefaultHttpClient httpclient=null;
试试{
HttpParams params=新的BasicHttpParams();
int m_超时=60000;
setTimeout(参数,m_timeout);
HttpConnectionParams.SetStaleCheckEnabled(参数,false);
HttpConnectionParams.setSocketBufferSize(参数,8192);
HttpClientParams.setRedirecting(参数,false);
CookieStore CookieStore=新的BasicCookieStore();
适用于(饼干厨师:mCookies){
cookieStore.addCookie(库克);
}
httpclient=新的默认httpclient(参数);
httpclient.setCookieStore(cookieStore);
if(mHost!=null){
formAction=mHost+“/www/”+formAction;
}
否则{
形态=”http://localhost/www/“+形式;
}
HttpPost HttpPost=新的HttpPost(成形);
List-nvps=newarraylist();
添加(新的BasicNameValuePair(inputRootName,inputRootValue));
添加(新的BasicNameValuePair(onSubmitName,onSubmitVal));
setEntity(新的UrlEncodedFormEntity(nvps,HTTP.UTF_8));
HttpResponse response=httpclient.execute(httpost);
HttpEntity=response.getEntity();
如果(实体!=null){
StatusLine StatusLine=response.getStatusLine();
int statusCode=statusLine.getStatusCode();
如果(状态代码!=200){
}
Log.d(“test_runner”,“response.getStatusLine:+response.getStatusLine());
InputStream=entity.getContent();
InputStreamReader isr=新的InputStreamReader(is);
BufferedReader br=新的BufferedReader(isr);
字符串行=null;
而((line=br.readLine())!=null){
//System.out.println(“数据发送器:“+行”);
    private void doPost(String formAction, String inputRootValue,
        String inputRootName, String onSubmitName, String onSubmitVal) {

    StringBuilder buff = new StringBuilder();

    DefaultHttpClient httpclient = null;

    try {  

    HttpParams params = new BasicHttpParams();
    int m_timeout = 60000;
    ConnManagerParams.setTimeout(params, m_timeout);            
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setSocketBufferSize(params, 8192);



    HttpClientParams.setRedirecting(params, false);


     CookieStore cookieStore = new BasicCookieStore(); 



     for(Cookie cook : mCookies){
         cookieStore.addCookie(cook); 
     }

     httpclient = new DefaultHttpClient(params);
     httpclient.setCookieStore(cookieStore);

     if(mHost != null){
         formAction =  mHost + "/www/" + formAction; 
     }
     else{
         formAction =  "http://localhost/www/" + formAction; 
     }




    HttpPost httpost = new HttpPost(formAction);

    List <NameValuePair> nvps = new ArrayList <NameValuePair>();
    nvps.add(new BasicNameValuePair(inputRootName, inputRootValue));
    nvps.add(new BasicNameValuePair(onSubmitName, onSubmitVal));


    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));




    HttpResponse response = httpclient.execute(httpost);

    HttpEntity entity = response.getEntity();

    if (entity != null) {

        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if(statusCode != 200){

        }

        Log.d("test_runner", "response.getStatusLine: " + response.getStatusLine());

        InputStream is = entity.getContent();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ( (line = br.readLine()) != null) {
            //System.out.println("Data Sender: " +  line);

            buff.append(line).append("\n");


        }
        is.close();

        //entity.consumeContent();
    } else {

    }

    Log.d("test_runner", "response: " + buff.toString());



} catch (Exception e) {
    Log.e("test_runner", ThrowableToString.fromThrowableToString(e));
}

if (httpclient != null) {
    // resource cleanup
    httpclient.getConnectionManager().shutdown();
}


}